Programs & Examples On #Undefined behavior

The unpredictable outcome of compiling or executing a program which breaks rules of the language neither compiler, interpreter nor runtime-system have to enforce.

What is the strict aliasing rule?

Strict aliasing doesn't refer only to pointers, it affects references as well, I wrote a paper about it for the boost developer wiki and it was so well received that I turned it into a page on my consulting web site. It explains completely what it is, why it confuses people so much and what to do about it. Strict Aliasing White Paper. In particular it explains why unions are risky behavior for C++, and why using memcpy is the only fix portable across both C and C++. Hope this is helpful.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Undefined behavior and sequence points

C++98 and C++03

This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.


Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

Pre-requisites : An elementary knowledge of C++ Standard


What are Sequence Points?

The Standard says

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

Side effects? What are side effects?

Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

For example:

int x = y++; //where y is also an int

In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.


What are the common sequence points listed in the C++ Standard ?

Those are:

  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

    Example :

    int a = 5; // ; is a sequence point here
    
  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

    • a && b (§5.14)
    • a || b (§5.15)
    • a ? b : c (§5.16)
    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.


What is Undefined Behaviour?

The Standard defines Undefined Behaviour in Section §1.3.12 as

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.


What is the relation between Undefined Behaviour and Sequence Points?

Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

For example:

int x = 5, y = 6;

int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

Another example here.


Now the Standard in §5/4 says

  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

From the above sentence the following expressions invoke Undefined Behaviour:

i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i;     // UB, same as above
++i = 2;     // UB, same as above
i = ++i + 1; // UB, same as above
++++++i;     // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

But the following expressions are fine:

i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i);   // well defined 
int j = i;
j = (++i, i++, j*i); // well defined

  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

Example 1:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

Example 2:

a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

Example 3 :

int x = i + i++ ;// Similar to above

Follow up answer for C++11 here.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I was getting this error message when trying to close the dialog by using a button inside the dialog body. I tried to use $('#myDialog').dialog('close'); which did not work.

I ended up firing the click action of the 'x' button on the header using:

$('.modal-header:first').find('button:first').click();  

Stop MySQL service windows

For Windows there's a couple of tricks to take care of...

(Assuming you've installed MySQL from Oracle's site but maybe have chosen not to run the service at startup)...

  1. To use "mysqld stop" from the command line for WinVista/Win7 you must right click on Start -> All Programs -> Accessories -> Command Prompt -> Run As Administrator

  2. Now that you have local OS admin access you can use "mysqld stop" (which will simply return)

IF YOU SEE THE FOLLOWING YOU ARE TRYING IT WITH A USER/COMMAND PROMPT THAT DOES NOT HAVE THE CORRECT PRIVILEGES:

121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Note] Plugin 'FEDERATED' is disabled.
121228 11:54:50 InnoDB: The InnoDB memory heap is disabled
121228 11:54:50 InnoDB: Mutexes and rw_locks use Windows interlocked functions
121228 11:54:50 InnoDB: Compressed tables use zlib 1.2.3
121228 11:54:50 InnoDB: Initializing buffer pool, size = 128.0M
121228 11:54:50 InnoDB: Completed initialization of buffer pool
121228 11:54:50  InnoDB: Operating system error number 5 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory. It may also be you have created a subdirectory
InnoDB: of the same name as a data file.
InnoDB: File name .\ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.

If mysqld does not appear as a known system command, try adding it to your class path

  1. Right click on My Computer
  2. Advanced System Settings
  3. Environment Variables
  4. System variables
  5. look for and left click select the variable named path
  6. click on "Edit" and copy out the string to notepad and append at the end the full path to your MySQL bin directory , e.g.

    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\MySQL\MySQL Server 5.5\bin

How to prove that a problem is NP complete?

You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:

It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.

See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.

Reversing a String with Recursion in Java

The call to the reverce(substring(1)) wil be performed before adding the charAt(0). since the call are nested, the reverse on the substring will then be called before adding the ex-second character (the new first character since this is the substring)

reverse ("ello") + "H" = "olleH"
--------^-------
reverse ("llo") + "e" = "olle"
---------^-----
reverse ("lo") + "l" = "oll"
--------^-----
reverse ("o") + "l" = "ol"
---------^----
"o" = "o"

Random "Element is no longer attached to the DOM" StaleElementReferenceException

You can solve this by using explicit wait so that you don't have to use hard wait.

If you fetching all the elements with one property and iterating through it using for each loop you can use wait inside the loop like this,

List<WebElement> elements = driver.findElements("Object property");
for(WebElement element:elements)
{
    new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfAllElementsLocatedBy("Object property"));
    element.click();//or any other action
}

or for single element you can use below code,

new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfAllElementsLocatedBy("Your object property"));
driver.findElement("Your object property").click();//or anyother action 

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !

Validate SSL certificates with Python

Or simply make your life easier by using the requests library:

import requests
requests.get('https://somesite.com', cert='/path/server.crt', verify=True)

A few more words about its usage.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

From our side it was using spdy with proxy cache. When the cache expires we get this error till the cache has been updated.

How to create a stopwatch using JavaScript?

This is my simple take on this question, I hope it helps someone out oneday, somewhere...

_x000D_
_x000D_
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;

function timer() {
    ms++;
    if(ms >= 100){
        sec++
        ms = 0
    }
    if(sec === 60){
        min++
        sec = 0
    }
    if(min === 60){
        ms, sec, min = 0;
    }

    //Doing some string interpolation
    let milli = ms < 10 ? `0`+ ms : ms;
    let seconds = sec < 10 ? `0`+ sec : sec;
    let minute = min < 10 ? `0` + min : min;

    let timer= `${minute}:${seconds}:${milli}`;
    output.innerHTML =timer;
};
//Start timer
function start(){
 time = setInterval(timer,10);
}
//stop timer
function stop(){
    clearInterval(time)
}
//reset timer
function reset(){
    ms = 0;
    sec = 0;
    min = 0;

    output.innerHTML = `00:00:00`
}
const startBtn = document.getElementById('startBtn');
const stopBtn =  document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');

startBtn.addEventListener('click',start,false);
stopBtn.addEventListener('click',stop,false);
resetBtn.addEventListener('click',reset,false);
_x000D_
    <p class="stopwatch" id="stopwatch">
        <!-- stopwatch goes here -->
    </p>
    <button class="btn-start" id="startBtn">Start</button>
    <button class="btn-stop" id="stopBtn">Stop</button>
    <button class="btn-reset" id="resetBtn">Reset</button>
_x000D_
_x000D_
_x000D_

Node.js request CERT_HAS_EXPIRED

The best way to fix this:

Renew the certificate. This can be done for free using Greenlock which issues certificates via Let's Encrypt™ v2

A less insecure way to fix this:

'use strict';

var request = require('request');
var agentOptions;
var agent;

agentOptions = {
  host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};

agent = new https.Agent(agentOptions);

request({
  url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
  // ...
});

By using an agent with rejectUnauthorized you at least limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.

Other Options

If you were using a self-signed cert you would add this option:

agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];

For trusted-peer connections you would also add these 2 options:

agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;

Bad Idea

It's unfortunate that process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop https has a way of passing agent options through. Those that don't should be fixed.

Bootstrap table striped: How do I change the stripe background colour?

Delete table-striped Its overriding your attempts to change row color.

Then do this In css

   tr:nth-child(odd) {
    background-color: lightskyblue;
    }

   tr:nth-child(even) {
    background-color: lightpink;
    }

    th {
       background-color: lightseagreen;
    }

CSS Printing: Avoiding cut-in-half DIVs between pages?

page-break-inside: avoid; gave me trouble using wkhtmltopdf.

To avoid breaks in the text add display: table; to the CSS of the text-containing div.

I hope this works for you too. Thanks JohnS.

Command copy exited with code 4 when building - Visual Studio restart solves it

As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Thanks for Ben's solution, my use case to display only particular fields in order

with object

Code:

    handlebars.registerHelper('eachToDisplayProperty', function(context, toDisplays, options) {
    var ret = "";
    var toDisplayKeyList = toDisplays.split(",");
    for(var i = 0; i < toDisplayKeyList.length; i++) {
        toDisplayKey = toDisplayKeyList[i];
        if(context[toDisplayKey]) {
            ret = ret + options.fn({
                property : toDisplayKey,
                value : context[toDisplayKey]
            });
        }

    }
    return ret;
});

Source object:

   { locationDesc:"abc", name:"ghi", description:"def", four:"you wont see this"}

Template:

{{#eachToDisplayProperty this "locationDesc,description,name"}}
    <div>
        {{property}} --- {{value}}
    </div>
    {{/eachToDisplayProperty}}

Output:

locationDesc --- abc
description --- def
name --- ghi

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

Is there a way to crack the password on an Excel VBA Project?

I tried some of solutions above and none of them works for me (excel 2007 xlsm file). Then i found another solution that even retrieve password, not just crack it.

Insert this code into module, run it and give it some time. It will recover your password by brute force.

Sub PasswordBreaker()

'Breaks worksheet password protection.

Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ActiveSheet.ProtectContents = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

How can I make a list of lists in R?

As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:

> str(list_all)
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

And the most simple construction would be this:

> str(list(list(1, 2), list("a", "b")))
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

Uncaught SyntaxError: Unexpected token :

In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

Executing <script> elements inserted with .innerHTML

You should not use the innerHTML property but rather the appendChild method of the Node: a node in a document tree [HTML DOM]. This way you are able to later call your injected code.

Make sure that you understand that node.innerHTML is not the same as node.appendChild. You might want to spend some time on the Javascript Client Reference for more details and the DOM. Hope the following helps...

Sample injection works:

_x000D_
_x000D_
<!DOCTYPE HTML>
<html>
<head>
    <title>test</title>
    <script language="javascript" type="text/javascript">
        function doOnLoad() {
            addScript('inject',"function foo(){ alert('injected'); }");
        }
    
        function addScript(inject,code) {
            var _in = document.getElementById('inject');
            var scriptNode = document.createElement('script');
            scriptNode.innerHTML = code;
            _in.appendChild(scriptNode);
        }
    </script>
</head>
<body onload="doOnLoad();">
    <div id="header">some content</div>
    <div id="inject"></div>
    <input type="button" onclick="foo(); return false;" value="Test Injected" />
</body>
</html>
_x000D_
_x000D_
_x000D_

regards

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

Disable submit button on form submit

The following worked for me:

var form_enabled = true;
$().ready(function(){
       // allow the user to submit the form only once each time the page loads
       $('#form_id').on('submit', function(){
               if (form_enabled) {
                       form_enabled = false;
                       return true;
               }

               return false;
        });
});

This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)

Drawing in Java using Canvas

The following should work:

public static void main(String[] args)
{
    final String title = "Test Window";
    final int width = 1200;
    final int height = width / 16 * 9;

    //Creating the frame.
    JFrame frame = new JFrame(title);

    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    //Creating the canvas.
    Canvas canvas = new Canvas();

    canvas.setSize(width, height);
    canvas.setBackground(Color.BLACK);
    canvas.setVisible(true);
    canvas.setFocusable(false);


    //Putting it all together.
    frame.add(canvas);

    canvas.createBufferStrategy(3);

    boolean running = true;

    BufferStrategy bufferStrategy;
    Graphics graphics;

    while (running) {
        bufferStrategy = canvas.getBufferStrategy();
        graphics = bufferStrategy.getDrawGraphics();
        graphics.clearRect(0, 0, width, height);

        graphics.setColor(Color.GREEN);
        graphics.drawString("This is some text placed in the top left corner.", 5, 15);

        bufferStrategy.show();
        graphics.dispose();
    }
}

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

How can getContentResolver() be called in Android?

getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance of Context ( Activity or Service for example).

What does the "no version information available" error from linux dynamic linker mean?

The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.

You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.

Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)

Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)

You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html

To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.

How to change navigation bar color in iOS 7 or 6?

Insert the below code in didFinishLaunchingWithOptions() in AppDelegate.m

[[UINavigationBar appearance] setBarTintColor:[UIColor
    colorWithRed:26.0/255.0 green:184.0/255.0 blue:110.0/255.0 alpha:1.0]];

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

How to Get a Specific Column Value from a DataTable?

I suggest such way based on extension methods:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

System.Data.DataSetExtensions.dll needs to be referenced.

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

Having the output of a console application in Visual Studio instead of the console

You have three possibilities to do this, but it's not trivial. The main idea of all IDEs is that all of them are the parents of the child (debug) processes. In this case, it is possible to manipulate with standard input, output and error handler. So IDEs start child applications and redirect out into the internal output window. I know about one more possibility, but it will come in future

  1. You could implement your own debug engine for Visual Studio. Debug Engine control starting and debugging for application. Examples for this you could find how to do this on docs.microsoft.com (Visual Studio Debug engine)
  2. Redirect form application using duplication of std handler for c++ or use Console.SetOut(TextWriter) for c#. If you need to print into the output window you need to use Visual Studio extension SDK. Example of the second variant you could find on Github.
  3. Start application that uses System.Diagnostics.Debug.WriteLine (for printing into output) and than it will start child application. On starting a child, you need to redirect stdout into parent with pipes. You could find an example on MSDN. But I think this is not the best way.

Tomcat is not deploying my web project from Eclipse

Same problem, not sure why it occurred only after upgrading from Spring v3.2.x to v4.2.x.

Solved it by doing the following:

  1. Clear all eclipse files [.classpath, .project, .settings/].
  2. Perform >mvn eclipse:eclipse
  3. Perform eclipse>project>properties>deployment assembly add [referenced projects, additional classpaths].

Publish and Start the module in Tomcat tab, it now starts properly.

JavaScript window resize event

jQuery is just wrapping the standard resize DOM event, eg.

window.onresize = function(event) {
    ...
};

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.

HTTP Request in Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

Or simpler:

URL("https://google.com").readText()

How to VueJS router-link active style

The :active pseudo-class is not the same as adding a class to style the element.

The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the mouse button is pressed down and ends when it is released.

What we are looking for is a class, such as .active, which we can use to style the navigation item.

For a clearer example of the difference between :active and .active see the following snippet:

_x000D_
_x000D_
li:active {_x000D_
  background-color: #35495E;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
  background-color: #41B883;_x000D_
}
_x000D_
<ul>_x000D_
  <li>:active (pseudo-class) - Click me!</li>_x000D_
  <li class="active">.active (class)</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


Vue-Router

vue-router automatically applies two active classes, .router-link-active and .router-link-exact-active, to the <router-link> component.


router-link-active

This class is applied automatically to the <router-link> component when its target route is matched.

The way this works is by using an inclusive match behavior. For example, <router-link to="/foo"> will get this class applied as long as the current path starts with /foo/ or is /foo.

So, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, both components would get the router-link-active class when the path is /foo/bar.


router-link-exact-active

This class is applied automatically to the <router-link> component when its target route is an exact match. Take into consideration that both classes, router-link-active and router-link-exact-active, will be applied to the component in this case.

Using the same example, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, the router-link-exact-activeclass would only be applied to <router-link to="/foo/bar"> when the path is /foo/bar.


The exact prop

Lets say we have <router-link to="/">, what will happen is that this component will be active for every route. This may not be something that we want, so we can use the exact prop like so: <router-link to="/" exact>. Now the component will only get the active class applied when it is an exact match at /.


CSS

We can use these classes to style our element, like so:

 nav li:hover,
 nav li.router-link-active,
 nav li.router-link-exact-active {
   background-color: indianred;
   cursor: pointer;
 }

The <router-link> tag was changed using the tag prop, <router-link tag="li" />.


Change default classes globally

If we wish to change the default classes provided by vue-router globally, we can do so by passing some options to the vue-router instance like so:

const router = new VueRouter({
  routes,
  linkActiveClass: "active",
  linkExactActiveClass: "exact-active",
})

Change default classes per component instance (<router-link>)

If instead we want to change the default classes per <router-link> and not globally, we can do so by using the active-class and exact-active-class attributes like so:

<router-link to="/foo" active-class="active">foo</router-link>

<router-link to="/bar" exact-active-class="exact-active">bar</router-link>

v-slot API

Vue Router 3.1.0+ offers low level customization through a scoped slot. This comes handy when we wish to style the wrapper element, like a list element <li>, but still keep the navigation logic in the anchor element <a>.

<router-link
  to="/foo"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  >
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  </li>
</router-link>

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

Android Transparent TextView?

setBackgroundColor(Color.TRANSPARENT);

The simplest way

Cast IList to List

In my case I had to do this, because none of the suggested solutions were available:

List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();

Java Class that implements Map and keeps insertion order?

You can use LinkedHashMap to main insertion order in Map

The important points about Java LinkedHashMap class are:

  1. It contains onlyunique elements.
  2. A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order

    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
    

But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.

Is it possible to start a shell session in a running container (without ssh)

Keep an eye on this pull request: https://github.com/docker/docker/pull/7409

Which implements the forthcoming docker exec <container_id> <command> utility. When this is available it should be possible to e.g. start and stop the ssh service inside a running container.

There is also nsinit to do this: "nsinit provides a handy way to access a shell inside a running container's namespace", but it looks difficult to get running. https://gist.github.com/ubergarm/ed42ebbea293350c30a6

How long do browsers cache HTTP 301s?

301 is a cacheable response per HTTP RFC and browsers will cache it depending on the HTTP caching headers you have on the response. Use FireBug or Charles to examine response headers to know the exact duration the response will be cached for.

If you would like to control the caching duration, you can use the the HTTP response headers Cache-Control and Expires to do the same. Alternatively, if you don't want to cache the 301 response at all, use the following headers.

Cache-Control: no-store, no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT

How to determine the version of the C++ standard used by the compiler?

Normally you should use __cplusplus define to detect c++17, but by default microsoft compiler does not define that macro properly, see https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ - you need to either modify project settings to include /Zc:__cplusplus switch, or you could use syntax like this:

#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
     //C++17 specific stuff here
#endif

Find elements inside forms and iframe using Java and Selenium WebDriver

By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:

SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance

dtImage.TableName="mydtimage";


if(!ds.Tables.Contains(dtImage.TableName))
        ds.Tables.Add(dtImage);

it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

How to fetch Java version using single line command in Linux

This way works for me.

# java -version 2>&1|awk '/version/ {gsub("\"","") ; print $NF}'

1.8.0_171

Better way to find last used row

How is this?

dim rownum as integer
dim colnum as integer
dim lstrow as integer
dim lstcol as integer
dim r as range

'finds the last row

lastrow = ActiveSheet.UsedRange.Rows.Count

'finds the last column

lastcol = ActiveSheet.UsedRange.Columns.Count

'sets the range

set r = range(cells(rownum,colnum), cells(lstrow,lstcol))

Check/Uncheck a checkbox on datagridview

// here is a simple way to do so

//irate through the gridview
            foreach (DataGridViewRow row in PifGrid.Rows)
            {
//store the cell (which is checkbox cell) in an object
                DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;

//check if the checkbox is checked or not
                bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);

//if its checked then uncheck it other wise check it
                if (!bChecked)
                {
                    row.Cells["Check"].Value = true;

                }
                else
                {
                    row.Cells["Check"].Value = false;

                }
            }

Differences between Ant and Maven

I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...

How do I get the resource id of an image if I know its name?

You can also try this:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName");
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.

Link: Dynamically Retrieving Resources in Android

No visible cause for "Unexpected token ILLEGAL"

If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.

  1. In nginx.conf sendfile off

  2. uwsgi application / config --disable-sendfile

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Is it possible to wait until all javascript files are loaded before executing javascript code?

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

Merge / convert multiple PDF files into one PDF

You can use the convert command directly,

e.g.

convert sub1.pdf sub2.pdf sub3.pdf merged.pdf

How to trim a file extension from a String in JavaScript?

Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';

    yourStr = yourStr.slice(0, -4); // 'test'

Are PHP Variables passed by value or by reference?

Depends on the version, 4 is by value, 5 is by reference.

How do I exit the Vim editor?

The q command with a number closes the given split in that position.

:q<split position> or :<split position>q will close the split in that position.

Let's say your Vim window layout is as follows:

-------------------------------------------------
|               |               |               |
-------------------------------------------------
|               |               |               |
|               |               |               |
|    Split 1    |    Split 2    |     Split 3   |
|               |               |               |
-------------------------------------------------

If you run the q1 command, it will close the first split. q2 will close the second split and vice versa.

The order of split position in the quit command does not matter. :2q or :q2 will close the second split.

If the split position you pass to the command is greater than the number of current splits, it will simply close the last split.

For example, if you run the q100 on the above window setup where there are only three splits, it will close the last split (Split 3).

The question has been asked here.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

How do I get the current GPS location programmatically in Android?

As of the second half of 2020, there is a much easier way to do this.

Excluding requesting permissions (which I will include at the bottom for devs newer to this), below is the code.

Just remember, you need to include at least this version of the library in your dependencies (in the app's build.gradle):

implementation 'com.google.android.gms:play-services-location:17.1.0'

... and of course the fine permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Kotlin (first the setup):

private val fusedLocationClient: FusedLocationProviderClient by lazy {
    LocationServices.getFusedLocationProviderClient(applicationContext)
}

private var cancellationTokenSource = CancellationTokenSource()

Then the main code (for FINE_LOCATION):

private fun requestCurrentLocation() {
    // Check Fine permission
    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {

        // Main code
        val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
            PRIORITY_HIGH_ACCURACY,
            cancellationTokenSource.token
        )

        currentLocationTask.addOnCompleteListener { task: Task<Location> ->
            val result = if (task.isSuccessful) {
                val result: Location = task.result
                "Location (success): ${result.latitude}, ${result.longitude}"
            } else {
                val exception = task.exception
                "Location (failure): $exception"
            }

            Log.d(TAG, "getCurrentLocation() result: $result")
        }
    } else {
        // Request fine location permission (full code below).
}

If you prefer Java, it looks like this:

public class JavaVersion extends AppCompatActivity {

    private final String TAG = "MainActivity";

    // The Fused Location Provider provides access to location APIs.
    private FusedLocationProviderClient fusedLocationClient;

    // Allows class to cancel the location request if it exits the activity.
    // Typically, you use one cancellation source per lifecycle.
    private final CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }
    ...
    
    private void requestCurrentLocation() {
        Log.d(TAG, "requestCurrentLocation()");
        // Request permission
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
            
            // Main code
            Task<Location> currentLocationTask = fusedLocationClient.getCurrentLocation(
                    PRIORITY_HIGH_ACCURACY,
                    cancellationTokenSource.getToken()
            );

            currentLocationTask.addOnCompleteListener((new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {

                    String result = "";

                    if (task.isSuccessful()) {
                        // Task completed successfully
                        Location location = task.getResult();
                        result = "Location (success): " +
                                location.getLatitude() +
                                ", " +
                                location.getLongitude();
                    } else {
                        // Task failed with an exception
                        Exception exception = task.getException();
                        result = "Exception thrown: " + exception;
                    }

                    Log.d(TAG, "getCurrentLocation() result: " + result);
                }
            }));
        } else {
            // TODO: Request fine location permission
            Log.d(TAG, "Request fine location permission.");
        }
    }
    ...
}

The arguments:

  1. PRIORITY type is self-explanatory. (Other options are PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, and PRIORITY_NO_POWER.)
  2. CancellationToken - This allows you to cancel the request if, for instance, the user navigates away from your Activity.

Example (Kotlin):

override fun onStop() {
    super.onStop()
    // Cancels location request (if in flight).
    cancellationTokenSource.cancel()
}

That's it.

Now, this does use the FusedLocationProviderClient which is a Google Play Services APIs.

That means this works on all Android devices with the Google Play Store (which is a lot of them). However, for devices in China without the Play Store, this won't work, so take that into account.

For developers who are a little newer to this, you need to request the fine (or coarse) location permission if the user hasn't approved it yet, so in the code above, I would request the location permission.

Below is the full code (in Kotlin).

I hope that helps (and makes your live's a little easier)!

/**
 * Demonstrates how to easily get the current location via the [FusedLocationProviderClient.getCurrentLocation].
 * The main code is in this class's requestCurrentLocation() method.
 */
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    // The Fused Location Provider provides access to location APIs.
    private val fusedLocationClient: FusedLocationProviderClient by lazy {
        LocationServices.getFusedLocationProviderClient(applicationContext)
    }

    // Allows class to cancel the location request if it exits the activity.
    // Typically, you use one cancellation source per lifecycle.
    private var cancellationTokenSource = CancellationTokenSource()

    // If the user denied a previous permission request, but didn't check "Don't ask again", this
    // Snackbar provides an explanation for why user should approve, i.e., the additional rationale.
    private val fineLocationRationalSnackbar by lazy {
        Snackbar.make(
            binding.container,
            R.string.fine_location_permission_rationale,
            Snackbar.LENGTH_LONG
        ).setAction(R.string.ok) {
            requestPermissions(
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root

        setContentView(view)
    }

    override fun onStop() {
        super.onStop()
        // Cancels location request (if in flight).
        cancellationTokenSource.cancel()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        Log.d(TAG, "onRequestPermissionResult()")

        if (requestCode == REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE) {
            when {
                grantResults.isEmpty() ->
                    // If user interaction was interrupted, the permission request
                    // is cancelled and you receive an empty array.
                    Log.d(TAG, "User interaction was cancelled.")

                grantResults[0] == PackageManager.PERMISSION_GRANTED ->
                    Snackbar.make(
                        binding.container,
                        R.string.permission_approved_explanation,
                        Snackbar.LENGTH_LONG
                    )
                        .show()

                else -> {
                    Snackbar.make(
                        binding.container,
                        R.string.fine_permission_denied_explanation,
                        Snackbar.LENGTH_LONG
                    )
                        .setAction(R.string.settings) {
                            // Build intent that displays the App settings screen.
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            val uri = Uri.fromParts(
                                "package",
                                BuildConfig.APPLICATION_ID,
                                null
                            )
                            intent.data = uri
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            startActivity(intent)
                        }
                        .show()
                }
            }
        }
    }

    fun locationRequestOnClick(view: View) {
        Log.d(TAG, "locationRequestOnClick()")

        requestCurrentLocation()
    }

    /**
     * Gets current location.
     * Note: The code checks for permission before calling this method, that is, it's never called
     * from a method with a missing permission. Also, I include a second check with my extension
     * function in case devs just copy/paste this code.
     */
    private fun requestCurrentLocation() {
        Log.d(TAG, "requestCurrentLocation()")
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED) {

            // Returns a single current location fix on the device. Unlike getLastLocation() that
            // returns a cached location, this method could cause active location computation on the
            // device. A single fresh location will be returned if the device location can be
            // determined within reasonable time (tens of seconds), otherwise null will be returned.
            //
            // Both arguments are required.
            // PRIORITY type is self-explanatory. (Other options are PRIORITY_BALANCED_POWER_ACCURACY,
            // PRIORITY_LOW_POWER, and PRIORITY_NO_POWER.)
            // The second parameter, [CancellationToken] allows the activity to cancel the request
            // before completion.
            val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
                PRIORITY_HIGH_ACCURACY,
                cancellationTokenSource.token
            )

            currentLocationTask.addOnCompleteListener { task: Task<Location> ->
                val result = if (task.isSuccessful) {
                    val result: Location = task.result
                    "Location (success): ${result.latitude}, ${result.longitude}"
                } else {
                    val exception = task.exception
                    "Location (failure): $exception"
                }

                Log.d(TAG, "getCurrentLocation() result: $result")
                logOutputToScreen(result)
            }
        } else {
            val provideRationale = shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)

            if (provideRationale) {
                fineLocationRationalSnackbar.show()
            } else {
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE)
            }
        }
    }

    private fun logOutputToScreen(outputString: String) {
        val finalOutput = binding.outputTextView.text.toString() + "\n" + outputString
        binding.outputTextView.text = finalOutput
    }

    companion object {
        private const val TAG = "MainActivity"
        private const val REQUEST_FINE_LOCATION_PERMISSIONS_REQUEST_CODE = 34
    }
}

Sublime Text 3, convert spaces to tabs

Use the following command to get it solved :

autopep8 -i <filename>.py

How to implement private method in ES6 class with Traceur

I came up with what I feel is a much better solution allowing:

  • no need for 'this._', that/self, weakmaps, symbols etc. Clear and straightforward 'class' code

  • private variables and methods are really private and have the correct 'this' binding

  • No use of 'this' at all which means clear code that is much less error prone

  • public interface is clear and separated from the implementation as a proxy to private methods

  • allows easy composition

with this you can do:

_x000D_
_x000D_
function Counter() {_x000D_
  // public interface_x000D_
  const proxy = {_x000D_
    advance,  // advance counter and get new value_x000D_
    reset,    // reset value_x000D_
    value     // get value_x000D_
  }_x000D_
 _x000D_
  // private variables and methods_x000D_
  let count=0;_x000D_
    _x000D_
  function advance() {_x000D_
    return ++count;_x000D_
  }_x000D_
     _x000D_
  function reset(newCount) {_x000D_
    count=(newCount || 0);_x000D_
  }_x000D_
     _x000D_
  function value() {_x000D_
    return count;_x000D_
  }_x000D_
    _x000D_
  return proxy;_x000D_
}_x000D_
     _x000D_
let counter=Counter.New();_x000D_
console.log(counter instanceof Counter); // true_x000D_
counter.reset(100);_x000D_
console.log('Counter next = '+counter.advance()); // 101_x000D_
console.log(Object.getOwnPropertyNames(counter)); // ["advance", "reset", "value"]
_x000D_
<script src="https://cdn.rawgit.com/kofifus/New/7987670c/new.js"></script>
_x000D_
_x000D_
_x000D_

see New for the code and more elaborate examples including constructor and composition

Check if string ends with certain pattern

You can use the substring method:

   String aString = "This.is.a.great.place.too.work.";
   String aSubstring = "work";
   String endString = aString.substring(aString.length() - 
        (aSubstring.length() + 1),aString.length() - 1);
   if ( endString.equals(aSubstring) )
       System.out.println("Equal " + aString + " " + aSubstring);
   else
       System.out.println("NOT equal " + aString + " " + aSubstring);

Node.js: Gzip compression?

Use gzip compression

Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the compression middleware for gzip compression in your Express app. For example:

var compression = require('compression');
var express = require('express')
var app = express()
app.use(compression())

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

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

How to remove html special chars?

In addition to the good answers above, PHP also has a built-in filter function that is quite useful: filter-var.

To remove HMTL characters, use:

$cleanString = filter_var($dirtyString, FILTER_SANITIZE_STRING);

More info:

  1. function.filter-var
  2. filter_sanitize_string

Is there a difference between "throw" and "throw ex"?

Throw preserves the stack trace. So lets say Source1 throws Error1 , its caught by Source2 and Source2 says throw then Source1 Error + Source2 Error will be available in the stack trace.

Throw ex does not preserve the stack trace. So all errors of Source1 will be wiped out and only Source2 error will sent to the client.

Sometimes just reading things are not clear , would suggest to watch this video demo to get more clarity , Throw vs Throw ex in C#.

Throw vs Throw ex

How to get a key in a JavaScript object by its value?

Underscore js solution

let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}

How to Debug Variables in Smarty like in PHP var_dump()

This should work:

{$var|@print_r}

or

{$var|@var_dump}

The @ is needed for arrays to make smarty run the modifier against the whole thing, otherwise it does it for each element.

Passing a String by Reference in Java?

java.lang.String is immutable.

I hate pasting URLs but https://docs.oracle.com/javase/10/docs/api/java/lang/String.html is essential for you to read and understand if you're in java-land.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

You can try with the following way,

 <parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
  </parent>

So that the parent jar will be fetching from the repository.

How to get the number of columns from a JDBC ResultSet?

Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);

//create statement
Statement stat = conn.createStatement();

//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");

//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();

//columns count from metadata object
int numOfCols = rsmd.getColumnCount();

But you can get more meta-informations about columns:

for(int i = 1; i <= numOfCols; i++)
{
    System.out.println(rsmd.getColumnName(i));
}

And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.

Format timedelta to string

I have a function:

def period(delta, pattern):
    d = {'d': delta.days}
    d['h'], rem = divmod(delta.seconds, 3600)
    d['m'], d['s'] = divmod(rem, 60)
    return pattern.format(**d)

Examples:

>>> td = timedelta(seconds=123456789)
>>> period(td, "{d} days {h}:{m}:{s}")
'1428 days 21:33:9'
>>> period(td, "{h} hours, {m} minutes and {s} seconds, {d} days")
'21 hours, 33 minutes and 9 seconds, 1428 days'

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

Does IMDB provide an API?

Yes, but not for free.

.....annual fees ranging from $15,000 to higher depending on the audience for the data and which data are being licensed.

URL :- http://www.imdb.com/licensing/

Java division by zero doesnt throw an ArithmeticException - why?

IEEE 754 defines 1.0 / 0.0 as Infinity and -1.0 / 0.0 as -Infinity and 0.0 / 0.0 as NaN.

By the way, floating point values also have -0.0 and so 1.0/ -0.0 is -Infinity.

Integer arithmetic doesn't have any of these values and throws an Exception instead.

To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.

if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
   throw new ArithmeticException("Not finite");

Get each line from textarea

$content = $_POST['content_name'];
$lines = explode("\n", $content);

foreach( $lines as $index => $line )
{
    $lines[$index] = $line . '<br/>';
}

// $lines contains your lines

How can I change my Cygwin home folder after installation?

I happen to use cwRsync (Cygwin + Rsync for Windows) where cygwin comes bundled, and I couldn't find /etc/passwd.

And it kept saying

Could not create directory '/home/username/.ssh'.
...
Failed to add the host to the list of known hosts (/home/username/.ssh/known_hosts).

So I wrote a batch file which changed the HOME variable before running rsync. Something like:

set HOME=.
rsync /path1 user@host:/path2

And voila! The .ssh folder appeared in the current working dir, and rsync stopped annoying with rsa fingerprints.

It's a quick hotfix, but later you should change HOME to a more secure location.

List all sequences in a Postgres db 8.1 with SQL

sequence info : max value

SELECT * FROM information_schema.sequences;

sequence info : last value

SELECT * FROM <sequence_name>

JAVA_HOME and PATH are set but java -version still shows the old one

$JAVA_HOME/bin/java -version says 'Permission Denied'

If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.

Do an

ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java

to see why you cannot access or run this program,.

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

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.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Try

(n+10).toString(36)

_x000D_
_x000D_
chr = n=>(n+10).toString(36);_x000D_
_x000D_
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);
_x000D_
_x000D_
_x000D_

Flask raises TemplateNotFound error even though template file exists

When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :

  1. the html file do not exist or
  2. when templates folder do not exist

To solve the problem :

create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.

How can I change image source on click with jQuery?

When you click the text or link the image will be changed to another image so you can use the below script helps to you to change image on click the link:

<script>
$(document).ready(function(){
$('li').click(function(){
var imgpath = $(this).attr('dir');
$('#image').html('<img src='+imgpath+'>');
});
$('.btn').click(function(){
$('#thumbs').fadeIn(500);
$('#image').animate({marginTop:'10px'},200);
$(this).hide();
$('#hide').fadeIn('slow');
});
$('#hide').click(function(){
$('#thumbs').fadeOut(500,function (){
$('#image').animate({marginTop:'50px'},200);
});
$(this).hide();
$('#show').fadeIn('slow');
});
});
</script>




 <div class="sandiv">
    <h1 style="text-align:center;">The  Human  Body  Parts :</h1>
    <div id="thumbs">
    <div class="sanl">
    <ul>
    <li dir="5.png">Human-body-organ-diag-1</li>
    <li dir="4.png">Human-body-organ-diag-2</li>
    <li dir="3.png">Human-body-organ-diag-3</li>
    <li dir="2.png">Human-body-organ-diag-4</li>
    <li dir="1.png">Human-body-organ-diag-5</li>
    </ul>
    </div>
    </div>
    <div class="man">
    <div id="image">
    <img src="2.png" width="348" height="375"></div>
    </div>
    <div id="thumbs">
    <div class="sanr" >
    <ul>
    <li dir="5.png">Human-body-organ-diag-6</li>
    <li dir="4.png">Human-body-organ-diag-7</li>
    <li dir="3.png">Human-body-organ-diag-8</li>
    <li dir="2.png">Human-body-organ-diag-9</li>
    <li dir="1.png">Human-body-organ-diag-10</li>
    </ul>
    </div>
    </div>
    </div>

css:

<style>
body{ font-family:Tahoma, Geneva, sans-serif; color:#ccc; font-size:11px; margin:0; padding:0; background-color:#111111}
.sandiv{ width:980px;height:570px;margin:0 auto;margin-top:20px; padding:10px; background-color:#000;-webkit-box-shadow: 0 1px 2px #666;box-shadow: 0 1px 2px #666;}
#image{width:348px; height:375px; border-radius:100%;margin:0 auto; margin-top:50px; margin-bottom:20px;}
#thumb{width:400px;margin:0 auto; display:none;}
ul{list-style:none; padding:0; margin:0;}
 li{ width:auto ; height:50px; border-radius:100%; margin:5px; cursor:pointer; }
.sanl
{
 margin-top:50px;
 float:left;
 width:210px;
 margin-left:30px;
 margin-right:30px;
  }
.sanr
{
    margin-top:50px;
 float:left;
 width:210px;
 margin-left:60px;
 margin-right:30px;
}
.man
{
 float:left;
 width:350px;
 margin-left:30px;
 margin-right:30px; 
}
</style>

I think the above code is very useful to you. This code i get from here or demo here for your reference

SQL Server Express CREATE DATABASE permission denied in database 'master'

Addition to @Kho dir answer.

This also works if you are not able to create a database with the windows user. you just need to login with the SQL Server Authentication then repeat the process mentioned by @Kho dir.

React-router: How to manually invoke Link?

again this is JS :) this still works ....

var linkToClick = document.getElementById('something');
linkToClick.click();

<Link id="something" to={/somewhaere}> the link </Link>

MySQL Error 1093 - Can't specify target table for update in FROM clause

You could insert the desired rows' ids into a temp table and then delete all the rows that are found in that table.

which may be what @Cheekysoft meant by doing it in two steps.

Adding calculated column(s) to a dataframe in pandas

The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map and apply functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.

>>> d
    A   B  C
0  11  13  5
1   6   7  4
2   8   3  6
3   4   8  7
4   0   1  7
>>> (d.A + d.B) / d.C
0    4.800000
1    3.250000
2    1.833333
3    1.714286
4    0.142857
>>> d.A > d.C
0     True
1     True
2     True
3    False
4    False

If you need to use operations like max and min within a row, you can use apply with axis=1 to apply any function you like to each row. Here's an example that computes min(A, B)-C, which seems to be like your "lower wick":

>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0    6
1    2
2   -3
3   -3
4   -7

Hopefully that gives you some idea of how to proceed.

Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:

d['A'][:-1] < d['C'][1:]

and this does it the other way, telling you which rows have A less than the preceding row's C:

d['A'][1:] < d['C'][:-1]

Doing ['A"][:-1] slices off the last element of column A, and doing ['C'][1:] slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

You need a program that learns and improves classification accuracy organically from experience.

I'll suggest deep learning, with deep learning this becomes a trivial problem.

You can retrain the inception v3 model on Tensorflow:

How to Retrain Inception's Final Layer for New Categories.

In this case, you will be training a convolutional neural network to classify an object as either a coca-cola can or not.

JavaScript closure inside loops – simple practical example

You could use a declarative module for lists of data such as query-js(*). In these situations I personally find a declarative approach less surprising

var funcs = Query.range(0,3).each(function(i){
     return  function() {
        console.log("My value: " + i);
    };
});

You could then use your second loop and get the expected result or you could do

funcs.iterate(function(f){ f(); });

(*) I'm the author of query-js and therefor biased towards using it, so don't take my words as a recommendation for said library only for the declarative approach :)

JQUERY ajax passing value from MVC View to Controller

Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".

$.ajax({
      url:/ControllerName/ActionName,
      data: "id=" + Id + "&param2=" + param2,
      type: "GET",
      success: function(data){
            // code here
      },
      error: function(passParams){
           // code here
      }
});

Another alternative will be to use the data-ajax on a link.

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>

Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.

<div id="_content"></div>

Not really a direct answer to ur question but its some info u should be aware of ;).

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I had the same problem, to solve it set specific user from domain in iis -> action sidebar->Basic Settings -> Connect as... -> specific user

enter image description here

Extracting first n columns of a numpy matrix

If a is your array:

In [11]: a[:,:2]
Out[11]: 
array([[-0.57098887, -0.4274751 ],
       [-0.22279713, -0.51723555],
       [ 0.67492385, -0.69294472],
       [ 0.41086611,  0.26374238]])

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

Send multiple checkbox data to PHP via jQuery ajax()

var myCheckboxes = new Array();
$("input:checked").each(function() {
   data['myCheckboxes[]'].push($(this).val());
});

You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push

TypeError: Router.use() requires middleware function but got a Object

I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.

I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.

My typical file structure is as follows:

/lib

/routes

---index.js (controls the main navigation)

/page-one



/page-two



     ---index.js

(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHOD or router.METHOD needs to have module.exports = router; at the end)

If someone wants I will post a link to github template that implements express routing using best practices. let me know

Thanks Anirudh!!! for the great answer.

List submodules in a Git repository

Here is another way to parse Git submodule names from .gitmodules without the need for sed or fancy IFS settings. :-)

#!/bin/env bash

function stripStartAndEndQuotes {
  temp="${1%\"}"
  temp="${temp#\"}"
  echo "$temp"
}

function getSubmoduleNames {
  line=$1
  len=${#line} # Get line length
  stripStartAndEndQuotes "${line::len-1}" # Remove last character
}

while read line; do
  getSubmoduleNames "$line"
done < <(cat .gitmodules | grep "\[submodule.*\]" | cut -d ' ' -f 2-)

How do I count occurrence of duplicate items in array

I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);

How to remove "disabled" attribute using jQuery?

for removing the disabled properties

 $('#inputDisabled').removeAttr('Disabled');

for adding the disabled properties

 $('#inputDisabled').attr('disabled', 'disabled' );

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

It wasn't working for me. I run crontab with sudo, so I switched to root, did the above suggestions, and crontab would open in vim, but it still wouldn't from my user account. Finally I ran sudo select-editor from the user account and that did the trick.

How can I detect when an Android application is running in the emulator?

This code works for me

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
    // Emulator
}
else {
    // Device
}

In case that device does not have sim card, It retuns empty string:""

Since Android emulator always retuns "Android" as network operator, I use above code.

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

How can I make SMTP authenticated in C#

How do you send the message?

The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

Memory address of an object in C#

When you free that handle, the garbage collector is free to move the memory that was pinned. If you have a pointer to memory that's supposed to be pinned, and you un-pin that memory, then all bets are off. That this worked at all in 3.5 was probably just by luck. The JIT compiler and the runtime for 4.0 probably do a better job of object lifetime analysis.

If you really want to do this, you can use a try/finally to prevent the object from being un-pinned until after you've used it:

public static string Get(object a)
{
    GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
    try
    {
        IntPtr pointer = GCHandle.ToIntPtr(handle);
        return "0x" + pointer.ToString("X");
    }
    finally
    {
        handle.Free();
    }
}

Are nested try/except blocks in Python a good programming practice?

Just be careful - in this case the first finally is touched, but skipped too.

def a(z):
    try:
        100/z
    except ZeroDivisionError:
        try:
            print('x')
        finally:
            return 42
    finally:
        return 1


In [1]: a(0)
x
Out[1]: 1

C# ListView Column Width Auto

Use this:

yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

from here

Java 8 - Best way to transform a list: map or foreach?

I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).

Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:

Benchmark                         Mode  Samples    Score   Error  Units
SO28319064.forEach                avgt      100  187.310 ± 1.768  ms/op
SO28319064.map                    avgt      100  189.180 ± 1.692  ms/op
SO28319064.mapWithParallelStream  avgt      100   55,577 ± 0,782  ms/op

You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.

Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:

myFinalList = myListToParse.stream()
    .filter(Objects::nonNull)
    .map(this::doSomething)
    .collect(toList()); 

How can I rename a conda environment?

I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:

  • rename enviroment folder (old_name to new_name)

  • open shell and activate env with custom folder:

    conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"

  • now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:

    conda update numpy

  • after applying any action to package, the environment will show in env list. To check this, type:

    conda env list

How to push both value and key into PHP array

There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.

`$intial_content = array();

if (true) {
 $intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}`

How to have stored properties in Swift, the same way I had on Objective-C?

I tried using objc_setAssociatedObject as mentioned in a few of the answers here, but after failing with it a few times I stepped back and realized there is no reason I need that. Borrowing from a few of the ideas here, I came up with this code which simply stores an array of whatever my extra data is (MyClass in this example) indexed by the object I want to associate it with:

class MyClass {
    var a = 1
    init(a: Int)
    {
        self.a = a
    }
}

extension UIView
{
    static var extraData = [UIView: MyClass]()

    var myClassData: MyClass? {
        get {
            return UIView.extraData[self]
        }
        set(value) {
            UIView.extraData[self] = value
        }
    }
}

// Test Code: (Ran in a Swift Playground)
var view1 = UIView()
var view2 = UIView()

view1.myClassData = MyClass(a: 1)
view2.myClassData = MyClass(a: 2)
print(view1.myClassData?.a)
print(view2.myClassData?.a)

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Just install the latest version from nondefault repository:

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-4.7-dev

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

I rebooted to recovery then

adb root; adb adb remount system; 

worked for me my recovery is twrp v3.5

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

In order to work where either given number could be larger I wrote this:

function getRange(start, end) {
  return Array.from({
    length: 1 + Math.abs(end - start)
  }, (_, i) => end > start ? start + i : start - i);
}

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

CSS strikethrough different color from text?

This CSS3 will make you line through property more easier, and working fine.

span{
    text-decoration: line-through;
    text-decoration-color: red;
}

How to scale a BufferedImage

To scale an image, you need to create a new image and draw into it. One way is to use the filter() method of an AffineTransferOp, as suggested here. This allows you to choose the interpolation technique.

private static BufferedImage scale1(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp 
        = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    scaleOp.filter(before, after);
    return after;
}

Another way is to simply draw the original image into the new image, using a scaling operation to do the scaling. This method is very similar, but it also illustrates how you can draw anything you want in the final image. (I put in a blank line where the two methods start to differ.)

private static BufferedImage scale2(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_ARGB);
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp 
        = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    Graphics2D g2 = (Graphics2D) after.getGraphics();
    // Here, you may draw anything you want into the new image, but we're
    // drawing a scaled version of the original image.
    g2.drawImage(before, scaleOp, 0, 0);
    g2.dispose();
    return after;
}

Addendum: Results

To illustrate the differences, I compared the results of the five methods below. Here is what the results look like, scaled both up and down, along with performance data. (Performance varies from one run to the next, so take these numbers only as rough guidelines.) The top image is the original. I scale it double-size and half-size.

As you can see, AffineTransformOp.filter(), used in scaleBilinear(), is faster than the standard drawing method of Graphics2D.drawImage() in scale2(). Also BiCubic interpolation is the slowest, but gives the best results when expanding the image. (For performance, it should only be compared with scaleBilinear() and scaleNearest().) Bilinear seems to be better for shrinking the image, although it's a tough call. And NearestNeighbor is the fastest, with the worst results. Bilinear seems to be the best compromise between speed and quality. The Image.getScaledInstance(), called in the questionable() method, performed very poorly, and returned the same low quality as NearestNeighbor. (Performance numbers are only given for expanding the image.)

enter image description here

public static BufferedImage scaleBilinear(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_BILINEAR;
    return scale(before, scale, interpolation);
}

public static BufferedImage scaleBicubic(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_BICUBIC;
    return scale(before, scale, interpolation);
}

public static BufferedImage scaleNearest(BufferedImage before, double scale) {
    final int interpolation = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
    return scale(before, scale, interpolation);
}

@NotNull
private static 
BufferedImage scale(final BufferedImage before, final double scale, final int type) {
    int w = before.getWidth();
    int h = before.getHeight();
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, before.getType());
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp = new AffineTransformOp(scaleInstance, type);
    scaleOp.filter(before, after);
    return after;
}

/**
 * This is a more generic solution. It produces the same result, but it shows how you 
 * can draw anything you want into the newly created image. It's slower 
 * than scaleBilinear().
 * @param before The original image
 * @param scale The scale factor
 * @return A scaled version of the original image
 */
private static BufferedImage scale2(BufferedImage before, double scale) {
    int w = before.getWidth();
    int h = before.getHeight();
    // Create a new image of the proper size
    int w2 = (int) (w * scale);
    int h2 = (int) (h * scale);
    BufferedImage after = new BufferedImage(w2, h2, before.getType());
    AffineTransform scaleInstance = AffineTransform.getScaleInstance(scale, scale);
    AffineTransformOp scaleOp
            = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BILINEAR);

    Graphics2D g2 = (Graphics2D) after.getGraphics();
    // Here, you may draw anything you want into the new image, but we're just drawing
    // a scaled version of the original image. This is slower than 
    // calling scaleOp.filter().
    g2.drawImage(before, scaleOp, 0, 0);
    g2.dispose();
    return after;
}

/**
 * I call this one "questionable" because it uses the questionable getScaledImage() 
 * method. This method is no longer favored because it's slow, as my tests confirm.
 * @param before The original image
 * @param scale The scale factor
 * @return The scaled image.
 */
private static Image questionable(final BufferedImage before, double scale) {
    int w2 = (int) (before.getWidth() * scale);
    int h2 = (int) (before.getHeight() * scale);
    return before.getScaledInstance(w2, h2, Image.SCALE_FAST);
}

Div not expanding even with content inside

Floated elements don’t take up any vertical space in their containing element.

All of your elements inside #albumhold are floated, apart from #albumhead, which doesn’t look like it’d take up much space.

However, if you add overflow: hidden; to #albumhold (or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.

SQL Query for Selecting Multiple Records

You want to add the IN() clause to your WHERE

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)

If you have a list of Ids stored in a table you can also do this:

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (SELECT Id FROM table)

When using SASS how can I import a file from a different directory?

Looks like some changes to SASS have made possible what you've initially tried doing:

@import "../subdir/common";

We even got this to work for some totally unrelated folder located in c:\projects\sass:

@import "../../../../../../../../../../projects/sass/common";

Just add enough ../ to be sure you'll end up at the drive root and you're good to go.

Of course, this solution is far from pretty, but I couldn't get an import from a totally different folder to work, neither using I c:\projects\sass nor setting the environment variable SASS_PATH (from: :load_paths reference) to that same value.

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

xcode library not found

If you are using Pods to include the GoogleAnalytics iOS SDK into your project, it's worth noting that since the 3.0 release your Other Linker Flags needs to include -lGoogleAnalyticsServices not the old -lGoogleAnalytics

How do I replace a character in a string in Java?

You may also want to check to make sure your not replacing an occurrence that has already been replaced. You can use a regular expression with negative lookahead to do this.

For example:

String str = "sdasdasa&amp;adas&dasdasa";  
str = str.replaceAll("&(?!amp;)", "&amp;");

This would result in the string "sdasdasa&amp;adas&amp;dasdasa".

The regex pattern "&(?!amp;)" basically says: Match any occurrence of '&' that is not followed by 'amp;'.

How do I import a .bak file into Microsoft SQL Server 2012?

.bak is a backup file generated in SQL Server.

Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.

You restore database by using following command...

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery

You want to learn about how to restore .bak file follow the below link:

http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx

npm check and update package if needed

No additional packages, to just check outdated and update those which are, this command will do:

npm install $(npm outdated | cut -d' ' -f 1 | sed '1d' | xargs -I '$' echo '$@latest' | xargs echo)

How to set default value to the input[type="date"]

$date=date("Y-m-d");
echo"$date";
echo"<br>SELECT DATE: <input type='date'  name='date'  id='datepicker' 
value='$date' required >";

How to pass params with history.push/Link/Redirect in react-router v4?

React TypeScript with Hooks

From a Class

  this.history.push({
      pathname: "/unauthorized",
      state: { message: "Hello" },
    });

UnAuthorized Functional Component

interface IState {
  message?: string;
}

export default function UnAuthorized() {
  const location = useLocation();
  const message = (location.state as IState).message;

  return (
    <div className="jumbotron">
      <h6>{message}</h6>
    </div>
  );
}

What's a simple way to get a text input popup dialog box on an iPhone

In iOS 5 there is a new and easy way to this. I'm not sure if the implementation is fully complete yet as it's not a gracious as, say, a UITableViewCell, but it should definitly do the trick as it is now standard supported in the iOS API. You will not need a private API for this.

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"This is an example alert!" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
[alert release];

This renders an alertView like this (screenshot taken from the iPhone 5.0 simulator in XCode 4.2):

example alert with alertViewStyle set to UIAlertViewStylePlainTextInput

When pressing any buttons, the regular delegate methods will be called and you can extract the textInput there like so:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    NSLog(@"Entered: %@",[[alertView textFieldAtIndex:0] text]);
}

Here I just NSLog the results that were entered. In production code, you should probably keep a pointer to your alertView as a global variable or use the alertView tag to check if the delegate function was called by the appropriate UIAlertView but for this example this should be okay.

You should check out the UIAlertView API and you'll see there are some more styles defined.

Hope this helped!

-- EDIT --

I was playing around with the alertView a little and I suppose it needs no announcement that it's perfectly possible to edit the textField as desired: you can create a reference to the UITextField and edit it as normal (programmatically). Doing this I constructed an alertView as you specified in your original question. Better late than never, right :-)?

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeNumberPad;
alertTextField.placeholder = @"Enter your name";
[alert show];
[alert release];

This produces this alert:

UIAlertView that uses the UIAlertViewPlainTextInput alertStyle to ask a user name

You can use the same delegate method as I poster earlier to process the result from the input. I'm not sure if you can prevent the UIAlertView from dismissing though (there is no shouldDismiss delegate function AFAIK) so I suppose if the user input is invalid, you have to put up a new alert (or just reshow this one) until correct input was entered.

Have fun!

Key existence check in HashMap

Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // No such key
}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // Key might be present...
    if (map.containsKey(key)) {
       // Okay, there's a key but the value is null
    } else {
       // Definitely no such key
    }
}

Find location of a removable SD card

It is possible to find where any additional SD cards are mounted by reading /proc/mounts (standard Linux file) and cross-checking against vold data (/system/etc/vold.conf). And note, that the location returned by Environment.getExternalStorageDirectory() may not appear in vold configuration (in some devices it's internal storage that cannot be unmounted), but still has to be included in the list. However we didn't find a good way to describe them to the user.

Get underlined text with Markdown

In GitHub markdown <ins>text</ins>works just fine.

jQuery document.createElement equivalent?

Though this is a very old question, I thought it would be nice to update it with recent information;

Since jQuery 1.8 there is a jQuery.parseHTML() function which is now a preferred way of creating elements. Also, there are some issues with parsing HTML via $('(html code goes here)'), fo example official jQuery website mentions the following in one of their release notes:

Relaxed HTML parsing: You can once again have leading spaces or newlines before tags in $(htmlString). We still strongly advise that you use $.parseHTML() when parsing HTML obtained from external sources, and may be making further changes to HTML parsing in the future.

To relate to the actual question, provided example could be translated to:

this.$OuterDiv = $($.parseHTML('<div></div>'))
    .hide()
    .append($($.parseHTML('<table></table>'))
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

which is unfortunately less convenient than using just $(), but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like onclick though):

> $.parseHTML('<div onclick="a"></div><script></script>')
[<div onclick=?"a">?</div>?]

> $.parseHTML('<div onclick="a"></div><script></script>', document, true)
[<div onclick=?"a">?</div>?, <script>?</script>?]

Also, here's a benchmark from the top answer adjusted to the new reality:

JSbin Link

jQuery 1.9.1

  $.parseHTML:    88ms
  $($.parseHTML): 240ms
  <div></div>:    138ms
  <div>:          143ms
  createElement:  64ms

It looks like parseHTML is much closer to createElement than $(), but all the boost is gone after wrapping the results in a new jQuery object

Can I set variables to undefined or pass undefined as an argument?

You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

To properly test for undefined or null, use these:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

Fast way of finding lines in one file that are not in another?

Use combine from moreutils package, a sets utility that supports not, and, or, xor operations

combine file1 not file2

i.e give me lines that are in file1 but not in file2

OR give me lines in file1 minus lines in file2

Note: combine sorts and finds unique lines in both files before performing any operation but diff does not. So you might find differences between output of diff and combine.

So in effect you are saying

Find distinct lines in file1 and file2 and then give me lines in file1 minus lines in file2

In my experience, it's much faster than other options

How can I read the client's machine/computer name from the browser?

Try getting the client computer name in Mozilla Firefox by using the code given below.

netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 

var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;

Also, the same piece of code can be put as an extension, and it can called from your web page.

Please find the sample code below.

Extension code:

var myExtension = {
  myListener: function(evt) {

//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;    
  }
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage

Webpage Code:

<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{ 
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>

</form>
</body>
</html>

How to use comparison and ' if not' in python?

You can do:

if not (u0 <= u <= u0+step):
    u0 = u0+ step # change the condition until it is satisfied
else:
    do sth. # condition is satisfied

Using a loop:

while not (u0 <= u <= u0+step):
   u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied

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

Just Create New User for MySQL do not use root. there is a problem its security issue

sudo mysql -p -u root

Login into MySQL or MariaDB with root privileges

CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';

login and create a new user

GRANT ALL PRIVILEGES ON *.* TO 'magento121121'@'%' WITH GRANT OPTION;

and grant privileges to access "." and "@" "%" any location not just only 'localhost'

exit;

if you want to see your privilege table SHOW GRANTS; & Enjoy.

How to decompile a whole Jar file?

Note: This solution only works for Mac and *nix users.

I also tried to find Jad with no luck. My quick solution was to download MacJad that contains jad. Once you downloaded it you can find jad in [where-you-downloaded-macjad]/MacJAD/Contents/Resources/jad.

Get HTML code from website in C#

Here's an example of using the HttpWebRequest class to fetch a URL

private void buttonl_Click(object sender, EventArgs e) 
{ 
    String url = TextBox_url.Text;
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 
    StreamReader sr = new StreamReader(response.GetResponseStream()); 
    richTextBox1.Text = sr.ReadToEnd(); 
    sr.Close(); 
} 

String Array object in Java

Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.

Based on what it looks like you're trying to do, this will not work.

These arrays belong in your main class.

How to return value from Action()?

Use Func<T> rather than Action<T>.

Action<T> acts like a void method with parameter of type T, while Func<T> works like a function with no parameters and which returns an object of type T.

If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>.

C#: Converting byte array to string and printing out to console

I was in a predicament where I had a signed byte array (sbyte[]) as input to a Test class and I wanted to replace it with a normal byte array (byte[]) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.

I wrote a helper method to print out the initializer of a given byte[]:

public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder("new byte[] { ");
    foreach (var b in bytes)
    {
        sb.Append(b + ", ");
    }
    sb.Append("}");
    Console.WriteLine(sb.ToString());
}

You can use it like this:

var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }

The ouput is valid C# which can then just be copied into your code.

And just for completeness, here is the UnsignedBytesFromSignedBytes method:

// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
    var unsigned = new byte[signed.Length];
    Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
    return unsigned;
}

Loading basic HTML in Node.js

we can load the html document with connect frame work. I have placed my html document and the related images in the public folder of my project where the below code and node modules present.

//server.js
var http=require('http');
var connect=require('connect');

var app = connect()
  .use(connect.logger('dev'))
  .use(connect.static('public'))
  .use(function(req, res){
   res.end('hello world\n');
 })

http.createServer(app).listen(3000);

I have tried the readFile() method of fs, but it fails to load the images, that's why i have used the connect framework.

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

    public static void main(String[] args) throws Exception {

        TheClass c= new TheClass();

        System.out.println(c.getClass().getDeclaredField("theField").get(c));
    }
}

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

Why use Optional.of over Optional.ofNullable?

Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

CSS @media print issues with background-color;

Two solutions that work (on modern Chrome at least - haven't tested beyond):

  1. !important right in the regular css declaration works (not even in the @media print)
  2. Use svg

git: How to diff changed files versus previous versions after a pull?

There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse for more details. In this case, you probably want:

git diff HEAD@{1}

The @{1} means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.

I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do

git diff HEAD@{1} filename

This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.

What is path of JDK on Mac ?

Which Mac version are you using? try these paths

 /System/Library/Frameworks/JavaVM.framework/ OR
 /usr/libexec/java_home

This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X

Parse String date in (yyyy-MM-dd) format

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String cunvertCurrentDate="06/09/2015";
Date date = new Date();
date = df.parse(cunvertCurrentDate);

Upload files with FTP using PowerShell

I'm not gonna claim that this is more elegant than the highest-voted solution...but this is cool (well, at least in my mind LOL) in its own way:

$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"   

"open $server
user $user $password
binary  
cd $dir     
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in

As you can see, it uses that dinky built-in windows FTP client. Much shorter and straightforward, too. Yes, I've actually used this and it works!

CSS: On hover show and hide different div's at the same time?

Have you tried somethig like this?

.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}

<div class="showhim">HOVER ME
  <div class="showme">hai</div>
  <div class="hideme">bye</div>
</div>

I dont know any reason why it shouldn't be possible.

How to remove "onclick" with JQuery?

It is very easy using removeAttr.

$(element).removeAttr("onclick");

Directory Chooser in HTML page

Try this, I think it will work for you:

<input type="file" webkitdirectory directory multiple/>

You can find the demo of this at https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3 , and if you need further information you can find it here.

Docker error response from daemon: "Conflict ... already in use by container"

No issues with the latest kartoza/qgis-desktop

I ran

docker pull kartoza/qgis-desktop

followed by

docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest

I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.

How to find all combinations of coins when given some dollar value

If the currency system allows it, a simple greedy algorithm that takes as many of each coin as possible, starting with the highest value currency.

Otherwise, dynamic programming is required to find an optimal solution quickly since this problem is essentially the knapsack problem.

For example, if a currency system has the coins: {13, 8, 1}, the greedy solution would make change for 24 as {13, 8, 1, 1, 1}, but the true optimal solution is {8, 8, 8}

Edit: I thought we were making change optimally, not listing all the ways to make change for a dollar. My recent interview asked how to make change so I jumped ahead before finishing to read the question.

Display progress bar while doing some work in C#?

If you want a "rotating" progress bar, why not set the progress bar style to "Marquee" and using a BackgroundWorker to keep the UI responsive? You won't achieve a rotating progress bar easier than using the "Marquee" - style...

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;
    }
}

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();
}

State transition[][] = {
    //  A               B               C
    {
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error
    }
};

Resizing an iframe based on content

We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.

There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.

There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:

 www.foo.com/home.html, which iframes
 |-> www.bar.net/framed.html, which iframes
     |-> www.foo.com/helper.html

then home.html can communicate with framed.html (iframed) and helper.html (same domain).

 Communication options for each page:
 +-------------------------+-----------+-------------+-------------+
 |                         | home.html | framed.html | helper.html |
 +-------------------------+-----------+-------------+-------------+
 | www.foo.com/home.html   |    N/A    |     YES     |     YES     |
 | www.bar.net/framed.html |    NO     |     N/A     |     YES     |
 | www.foo.com/helper.html |    YES    |     YES     |     N/A     |
 +-------------------------+-----------+-------------+-------------+

framed.html can send messages to helper.html (iframed) but not home.html (child can't communicate cross-domain with parent).

The key here is that helper.html can receive messages from framed.html, and can also communicate with home.html.

So essentially, when framed.html loads, it works out its own height, tells helper.html, which passes the message on to home.html, which can then resize the iframe in which framed.html sits.

The simplest way we found to pass messages from framed.html to helper.html was through a URL argument. To do this, framed.html has an iframe with src='' specified. When its onload fires, it evaluates its own height, and sets the src of the iframe at this point to helper.html?height=N

There's an explanation here of how facebook handle it, which may be slightly clearer than mine above!


Code

In www.foo.com/home.html, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):

<script>
  // Resize iframe to full height
  function resizeIframe(height)
  {
    // "+60" is a general rule of thumb to allow for differences in
    // IE & and FF height reporting, can be adjusted as required..
    document.getElementById('frame_name_here').height = parseInt(height)+60;
  }
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>

In www.bar.net/framed.html:

<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>

<script type="text/javascript">
  function iframeResizePipe()
  {
     // What's the page height?
     var height = document.body.scrollHeight;

     // Going to 'pipe' the data to the parent through the helpframe..
     var pipe = document.getElementById('helpframe');

     // Cachebuster a precaution here to stop browser caching interfering
     pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();

  }
</script>

Contents of www.foo.com/helper.html:

<html> 
<!-- 
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content 
--> 
  <body onload="parentIframeResize()"> 
    <script> 
      // Tell the parent iframe what height the iframe needs to be
      function parentIframeResize()
      {
         var height = getParam('height');
         // This works as our parent's parent is on our domain..
         parent.parent.resizeIframe(height);
      }

      // Helper function, parse param from request string
      function getParam( name )
      {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
      }
    </script> 
  </body> 
</html>

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

Convert XML String to Object

Another way with an Advanced xsd to c# classes generation Tools : xsd2code.com. This tool is very handy and powerfull. It has a lot more customisation than the xsd.exe tool from Visual Studio. Xsd2Code++ can be customised to use Lists or Arrays and supports large schemas with a lot of Import statements.

Note of some features,

  • Generates business objects from XSD Schema or XML file to flexible C# or Visual Basic code.
  • Support Framework 2.0 to 4.x
  • Support strong typed collection (List, ObservableCollection, MyCustomCollection).
  • Support automatic properties.
  • Generate XML read and write methods (serialization/deserialization).
  • Databinding support (WPF, Xamarin).
  • WCF (DataMember attribute).
  • XML Encoding support (UTF-8/32, ASCII, Unicode, Custom).
  • Camel case / Pascal Case support.
  • restriction support ([StringLengthAttribute=true/false], [RegularExpressionAttribute=true/false], [RangeAttribute=true/false]).
  • Support large and complex XSD file.
  • Support of DotNet Core & standard

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Opening popup windows in HTML

I feel like this is the simplest way. (Feel free to change the width and height values).

<a href="http://www.google.com" 
target="popup" 
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>

MVC Razor view nested foreach's model

Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

Fast Linux file count for a large number of files

Surprisingly for me, a bare-bones find is very much comparable to ls -f

> time ls -f my_dir | wc -l
17626

real    0m0.015s
user    0m0.011s
sys     0m0.009s

versus

> time find my_dir -maxdepth 1 | wc -l
17625

real    0m0.014s
user    0m0.008s
sys     0m0.010s

Of course, the values on the third decimal place shift around a bit every time you execute any of these, so they're basically identical. Notice however that find returns one extra unit, because it counts the actual directory itself (and, as mentioned before, ls -f returns two extra units, since it also counts . and ..).

Get keys from HashMap in Java

Try this simple program:

public class HashMapGetKey {

public static void main(String args[]) {

      // create hash map

       HashMap map = new HashMap();

      // populate hash map

      map.put(1, "one");
      map.put(2, "two");
      map.put(3, "three");
      map.put(4, "four");

      // get keyset value from map

Set keyset=map.keySet();

      // check key set values

      System.out.println("Key set values are: " + keyset);
   }    
}

What version of javac built my jar?

You can easily do this on command line using following process :

If you know any of the class name in jar, you can use following command :

javap -cp jarname.jar -verbose packagename.classname | findstr major

example :

    C:\pathwherejarlocated> javap -cp jackson-databind-2.8.6.jar -verbose com.fasterxml.jackson.databind.JsonMappingException | findstr major

Output :

    major version: 51

Quick Reference :

JDK 1.0 — major version 45 
DK 1.1 — major version 45 
JDK 1.2 — major version 46 
JDK 1.3 — major version 47 
JDK 1.4 — major version 48 
JDK 1.5 — major version 49 
JDK 1.6 — major version 50 
JDK 1.7 — major version 51 
JDK 1.8 — major version 52 
JDK 1.9 — major version 53 

PS : if you dont know any of the classname, you can easily do this by using any of the jar decompilers or by simply using following command to extract jar file :

jar xf myFile.jar

How do I add a new column to a Spark DataFrame (using PySpark)?

You cannot add an arbitrary column to a DataFrame in Spark. New columns can be created only by using literals (other literal types are described in How to add a constant column in a Spark DataFrame?)

from pyspark.sql.functions import lit

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

df_with_x4 = df.withColumn("x4", lit(0))
df_with_x4.show()

## +---+---+-----+---+
## | x1| x2|   x3| x4|
## +---+---+-----+---+
## |  1|  a| 23.0|  0|
## |  3|  B|-23.0|  0|
## +---+---+-----+---+

transforming an existing column:

from pyspark.sql.functions import exp

df_with_x5 = df_with_x4.withColumn("x5", exp("x3"))
df_with_x5.show()

## +---+---+-----+---+--------------------+
## | x1| x2|   x3| x4|                  x5|
## +---+---+-----+---+--------------------+
## |  1|  a| 23.0|  0| 9.744803446248903E9|
## |  3|  B|-23.0|  0|1.026187963170189...|
## +---+---+-----+---+--------------------+

included using join:

from pyspark.sql.functions import exp

lookup = sqlContext.createDataFrame([(1, "foo"), (2, "bar")], ("k", "v"))
df_with_x6 = (df_with_x5
    .join(lookup, col("x1") == col("k"), "leftouter")
    .drop("k")
    .withColumnRenamed("v", "x6"))

## +---+---+-----+---+--------------------+----+
## | x1| x2|   x3| x4|                  x5|  x6|
## +---+---+-----+---+--------------------+----+
## |  1|  a| 23.0|  0| 9.744803446248903E9| foo|
## |  3|  B|-23.0|  0|1.026187963170189...|null|
## +---+---+-----+---+--------------------+----+

or generated with function / udf:

from pyspark.sql.functions import rand

df_with_x7 = df_with_x6.withColumn("x7", rand())
df_with_x7.show()

## +---+---+-----+---+--------------------+----+-------------------+
## | x1| x2|   x3| x4|                  x5|  x6|                 x7|
## +---+---+-----+---+--------------------+----+-------------------+
## |  1|  a| 23.0|  0| 9.744803446248903E9| foo|0.41930610446846617|
## |  3|  B|-23.0|  0|1.026187963170189...|null|0.37801881545497873|
## +---+---+-----+---+--------------------+----+-------------------+

Performance-wise, built-in functions (pyspark.sql.functions), which map to Catalyst expression, are usually preferred over Python user defined functions.

If you want to add content of an arbitrary RDD as a column you can

Best practice when adding whitespace in JSX

You can add simple white space with quotes sign: {" "}

Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):

`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

Detecting IE11 using CSS Capability/Feature Detection

Here's an answer for 2017 on, where you probably only care about distinguishing <=IE11 from >IE11 ("Edge"):

@supports not (old: ie) { /* code for not old IE here */ }

More demonstrative example:

body:before { content: 'old ie'; }
/**/@supports not (old: ie) {
body:before { content: 'not old ie'; }
/**/}

This works because IE11 doesn't actually even support @supports, and all other relevant browser/version combinations do.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

From the GNU UPC website:

Compiler build fails with fatal error: gnu/stubs-32.h: No such file or directory

This error message shows up on the 64 bit systems where GCC/UPC multilib feature is enabled, and it indicates that 32 bit version of libc is not installed. There are two ways to correct this problem:

  • Install 32 bit version of glibc (e.g. glibc-devel.i686 on Fedora, CentOS, ..)
  • Disable 'multilib' build by supplying "--disable-multilib" switch on the compiler configuration command

phpmyadmin logs out after 1440 secs

steps to change cookie expiration

step 1:Go to settings of Phpmyadmin

step 2:General

step 3:Login cookie validity

step 4:Update 1440 seconds default cookie expiration time with your new value

How to style a select tag's option element?

Unfortunately, WebKit browsers do not support styling of <option> tags yet, except for color and background-color.

The most widely used cross browser solution is to use <ul> / <li> and style them using CSS. Frameworks like Bootstrap do this well.

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

json parsing error syntax error unexpected end of input

May be it will be useful.

The method parameter name should be the same like it has JSON

It will work fine

C#

public ActionResult GetMTypes(int id)

JS

 var params = { id: modelId  };
                 var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
                 $.ajax({
                     type: "POST",
                     url: url,
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     data: JSON.stringify(params),

It will NOT work fine

C#

public ActionResult GetMTypes(int modelId)

JS

 var params = { id: modelId  };
                 var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
                 $.ajax({
                     type: "POST",
                     url: url,
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     data: JSON.stringify(params),

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

Spring Boot access static resources missing scr/main/resources

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile() when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

Below is the code snippet for the same -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

Maven: How to include jars, which are not available in reps into a J2EE project?

For people wanting a quick solution to this problem:

<dependency>
  <groupId>LIB_NAME</groupId>
  <artifactId>LIB_NAME</artifactId>
  <version>1.0.0</version>
  <scope>system</scope>
  <systemPath>${basedir}/WebContent/WEB-INF/lib/YOUR_LIB.jar</systemPath>
</dependency>

just give your library a unique groupID and artifact name and point to where it is in the file system. You are good to go.

Of course this is a dirty quick fix that will ONLY work on your machine and if you don't change the path to the libs. But some times, that's all you want, to run and do a few tests.

EDIT: just re-red the question and realised the user was already using my solution as a temporary fix. I'll leave my answer as a quick help for others that come to this question. If anyone disagrees with this please leave me a comment. :)

How to drop a table if it exists?

In SQL Server 2016 (13.x) and above

DROP TABLE IF EXISTS dbo.Scores

In earlier versions

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
DROP TABLE dbo.Scores; 

U is your table type

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

Using Mockito, how do I verify a method was a called with a certain argument?

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");

Then inject the mock into m_orderSvc and call your method.

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Finally, verify that the mock was called properly:

verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");

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

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

In Rails, how do you render JSON using a view?

Try adding a view users/show.json.erb This should be rendered when you make a request for the JSON format, and you get the added benefit of it being rendered by erb too, so your file could look something like this

{
    "first_name": "<%= @user.first_name.to_json %>",
    "last_name": "<%= @user.last_name.to_json %>"
}

How to get only numeric column values?

SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1

Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.

To filter out columns containing non-digit characters (and empty strings), you could use

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''