Programs & Examples On #Code conversion

How to convert a Kotlin source file to a Java source file

You can compile Kotlin to bytecode, then use a Java disassembler.

The decompiling may be done inside IntelliJ Idea, or using FernFlower https://github.com/fesh0r/fernflower (thanks @Jire)

There was no automated tool as I checked a couple months ago (and no plans for one AFAIK)

Is there an easy way to convert jquery code to javascript?

I just found this quite impressive tutorial about jquery to javascript conversion from Jeffrey Way on Jan 19th 2012 *Copyright © 2014 Envato* :

http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/

Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!

In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.

I proposed it in a comment to OP, and after his suggestion, i publish it has an answer for everyone to refer to.

Also, Jeffrey Way mentioned about his inspiration witch seems to be a good primer for understanding : http://sharedfil.es/js-48hIfQE4XK.html

Has a teaser, this document comparison of jQuery to javascript :

$(document).ready(function() {
  // code…
});

document.addEventListener("DOMContentLoaded", function() {
  // code…
});

$("a").click(function() {
  // code…
})

[].forEach.call(document.querySelectorAll("a"), function(el) {
  el.addEventListener("click", function() {
    // code…
  });
});

You should take a look.

Wildcards in a Windows hosts file

I found a posting about Using the Windows Hosts File that also says "No wildcards are allowed."

In the past, I have just added the additional entries to the hosts file, because (as previously said), it's not that much extra work when you already are editing the apache config file.

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

Function to check if a string is a date

Here's a different approach without using a regex:

function check_your_datetime($x) {
    return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?

The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

Reset auto increment counter in postgres

Note that if you have table name with '_', it is removed in sequence name.

For example, table name: user_tokens column: id Sequence name: usertokens_id_seq

How to handle static content in Spring MVC?

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

how to access downloads folder in android?

Updated

getExternalStoragePublicDirectory() is deprecated.

To get the download folder from a Fragment,

val downloadFolder = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

From an Activity,

val downloadFolder = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

downloadFolder.listFiles() will list the Files.

downloadFolder?.path will give you the String path of the download folder.

How to implement the factory method pattern in C++ correctly

You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus

The best solution is on the "comments and discussions", see the "No need for static Create methods".

From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.

#ifndef FACTORY_H
#define FACTORY_H

#include <QMap>
#include <QString>

template <typename T>
class Factory
{
public:
    template <typename TDerived>
    void registerType(QString name)
    {
        static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
        _createFuncs[name] = &createFunc<TDerived>;
    }

    T* create(QString name) {
        typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
        if (it != _createFuncs.end()) {
            return it.value()();
        }
        return nullptr;
    }

private:
    template <typename TDerived>
    static T* createFunc()
    {
        return new TDerived();
    }

    typedef T* (*PCreateFunc)();
    QMap<QString,PCreateFunc> _createFuncs;
};

#endif // FACTORY_H

Sample usage:

Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");

What is the difference between Cygwin and MinGW?

To add to the other answers, Cygwin comes with the MinGW libraries and headers and you can compile without linking to the cygwin1.dll by using -mno-cygwin flag with gcc. I greatly prefer this to using plain MinGW and MSYS.

An item with the same key has already been added

In MVC 5 I found that temporarily commenting out references to an Entity Framework model, and recompiling the project side stepped this error when scaffolding. Once I finish scaffolding I uncomment the code.

public Guid CreatedById { get; private set; }
// Commented out so I can scaffold: 
// public virtual UserBase CreatedBy { get; private set; }

How to replace ${} placeholders in a text file?

It can be done in bash itself if you have control of the configuration file format. You just need to source (".") the configuration file rather than subshell it. That ensures the variables are created in the context of the current shell (and continue to exist) rather than the subshell (where the variable disappear when the subshell exits).

$ cat config.data
    export parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA
    export parm_user=pax
    export parm_pwd=never_you_mind

$ cat go.bash
    . config.data
    echo "JDBC string is " $parm_jdbc
    echo "Username is    " $parm_user
    echo "Password is    " $parm_pwd

$ bash go.bash
    JDBC string is  jdbc:db2://box7.co.uk:5000/INSTA
    Username is     pax
    Password is     never_you_mind

If your config file cannot be a shell script, you can just 'compile' it before executing thus (the compilation depends on your input format).

$ cat config.data
    parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA # JDBC URL
    parm_user=pax                              # user name
    parm_pwd=never_you_mind                    # password

$ cat go.bash
    cat config.data
        | sed 's/#.*$//'
        | sed 's/[ \t]*$//'
        | sed 's/^[ \t]*//'
        | grep -v '^$'
        | sed 's/^/export '
        >config.data-compiled
    . config.data-compiled
    echo "JDBC string is " $parm_jdbc
    echo "Username is    " $parm_user
    echo "Password is    " $parm_pwd

$ bash go.bash
    JDBC string is  jdbc:db2://box7.co.uk:5000/INSTA
    Username is     pax
    Password is     never_you_mind

In your specific case, you could use something like:

$ cat config.data
    export p_p1=val1
    export p_p2=val2
$ cat go.bash
    . ./config.data
    echo "select * from dbtable where p1 = '$p_p1' and p2 like '$p_p2%' order by p1"
$ bash go.bash
    select * from dbtable where p1 = 'val1' and p2 like 'val2%' order by p1

Then pipe the output of go.bash into MySQL and voila, hopefully you won't destroy your database :-).

How to open Emacs inside Bash

Just type emacs -nw. This won't open an X window.

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Call Jquery function

Try this code:

$(document).ready(function(){
    $('#YourControlID').click(function(){
        if() { //your condition
            $.messager.show({  
                title:'My Title',  
                msg:'The message content',  
                showType:'fade',  
                style:{  
                    right:'',  
                    bottom:''  
                }  
            });  
        }
    });
});

How to remove a field completely from a MongoDB document?

{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } }

Ans:

db.tablename.remove({'tags.words':['abc','123']})

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

Best way to incorporate Volley (or other library) into Android Studio project

LATEST UPDATE:

Use the official version from jCenter instead.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

The dependencies below points to deprecated volley that is no longer maintained.

ORIGINAL ANSWER

You can use this in dependency section of your build.gradle file to use volley

  dependencies {
      compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  }

UPDATED:

Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.

https://github.com/mcxiaoke/android-volley

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

You can simply add this line into your bootstrap_and_overides.css.less file

body { background: #000000 !important;}

that's it

Mongoose, update values in array of objects

In mongoose we can update, like simple array

user.updateInfoByIndex(0,"test")

User.methods.updateInfoByIndex = function(index, info) ={
    this.arrayField[index]=info
    this.save()
}

Why Doesn't C# Allow Static Methods to Implement an Interface?

C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.

That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.

Laravel 5 Eloquent where and or in Clauses

Also, if you have a variable,

CabRes::where('m_Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) use ($variable){
          $q->where('Cab', 2)
            ->orWhere('Cab', $variable);
      })
      ->get();

Does C# have an equivalent to JavaScript's encodeURIComponent()?

I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this

c# CODE:

string a = "!@#$%^&*()_+ some text here ??? ??????? ????";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");

the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83

After you decode It with Javascript's decodeURLComponent();

you will get this: !@#$%^&*()_+ some text here ??? ??????? ????

Thank You for attention

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

Do I commit the package-lock.json file created by npm 5?

Yes, it's a standard practice to commit package-lock.json.

The main reason for committing package-lock.json is that everyone in the project is on the same package version.

Pros:

  • If you follow strict versioning and don't allow updating to major versions automatically to save yourself from backward-incompatible changes in third-party packages committing package-lock helps a lot.
  • If you update a particular package, it gets updated in package-lock.json and everyone using the repository gets updated to that particular version when they take the pull of your changes.

Cons:

  • It can make your pull requests look ugly :)

npm install won't make sure that everyone in the project is on the same package version. npm ci will help with this.

Clicking submit button of an HTML form by a Javascript code

document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

How to compile C program on command line using MinGW?

If you pasted your text into the path variable and added a whitespace before the semicolon, you should delete that and add a backslash at the end of the directory (;C:\Program Files (x86)\CodeBlocks\MinGW\bin

How to send multiple data fields via Ajax?

The correct syntax is:

data: {status: status, name: name},

As specified here: http://api.jquery.com/jQuery.ajax/

So if that doesn't work, I would alert those variables to make sure they have values.

Text-decoration: none not working

There are no underline even I deleted 'text-decoration: none;' from your code. But I had a similar experience.

Then I added a Code

a{
 text-decoration: none;
}

and

a:hover{
 text-decoration: none;
}

So, try your code with :hover.

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

git visual diff between branches

You can use the free P4Merge from Perforce to do this as well:

http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools

enter image description here

Details on integrating it with Git can be found here and here

but a quick summary from the above links is:

  • Put the following bits in your ~/.gitconfig, and then you can do $ git mergetool and $ git difftool to use p4merge
  • Note that $ git diff will still just use the default inline diff viewer :) (tested with git version 1.8.2)

Changes for .gitconfig

[merge]
  keepBackup = false
    tool = p4merge
[mergetool "p4merge"]
    cmd = /Applications/p4merge.app/Contents/Resources/launchp4merge "\"$PWD/$BASE\"" "\"$PWD/$REMOTE\"" "\"$PWD/$LOCAL\"" "\"$PWD/$MERGED\""
    keepTemporaries = false
    trustExitCode = false
    keepBackup = false
[diff]
    tool = p4merge
[difftool "p4merge"]
    cmd = /Applications/p4merge.app/Contents/Resources/launchp4merge "\"$REMOTE\"" "\"$LOCAL\""

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

Printing the last column of a line in a file

ls -l | awk '{print $9}' | tail -n1

find difference between two text files with one item per line

If you want to use loops You can try like this: (diff and cmp are much more efficient. )

while read line
do
    flag = 0
    while read line2
    do
       if ( "$line" = "$line2" )
        then
            flag = 1
        fi
     done < file1 
     if ( flag -eq 0 )
     then
         echo $line > file3
     fi
done < file2

Note: The program is only to provide a basic insight into what can be done if u dont want to use system calls such as diff n comm..

Git Push error: refusing to update checked out branch

I got this error when I was playing around while reading progit. I made a local repository, then fetched it in another repo on the same file system, made an edit and tried to push. After reading NowhereMan's answer, a quick fix was to go to the "remote" directory and temporarily checkout another commit, push from the directory I made changes in, then go back and put the head back on master.

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

How to connect from windows command prompt to mysql command line

  1. Start your MySQL server service from MySQL home directory. Your one is C:\MYSQL\bin\ so choose this directory in command line and type: NET START MySQL
    (After that you can open Windows Task Manager and verify in Processes tab is mysqld.exe process running. Maybe your problem is here.)
  2. Type: mysql -u user -p [pressEnter]
  3. Type your password [pressEnter]

or make a start.bat file:

  1. add C:\MYSQL\bin\ to your PATH
  2. write a start.bat file
  3. My start.bat file has only two lines like below:
    net start MySQL
    mysql -u root -p

Good luck!

How to quickly edit values in table in SQL Server Management Studio?

In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.

But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

What is the difference between _tmain() and main() in C++?

_tmain does not exist in C++. main does.

_tmain is a Microsoft extension.

main is, according to the C++ standard, the program's entry point. It has one of these two signatures:

int main();
int main(int argc, char* argv[]);

Microsoft has added a wmain which replaces the second signature with this:

int wmain(int argc, wchar_t* argv[]);

And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain which, if Unicode is enabled, is compiled as wmain, and otherwise as main.

As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain should take a wchar_t argument, not char. Since the compiler doesn't enforce this for the main function, you get a program where an array of wchar_t strings are passed to the main function, which interprets them as char strings.

Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes \0 followed by the ASCII value.

And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.

And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.

In general, you have three options when doing Windows programming:

  • Explicitly use Unicode (call wmain, and for every Windows API function which takes char-related arguments, call the -W version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using char use wchar_t, and so on
  • Explicitly disable Unicode. Call main, and CreateWindowA, and use char for strings.
  • Allow both. (call _tmain, and CreateWindow, which resolve to main/_tmain and CreateWindowA/CreateWindowW), and use TCHAR instead of char/wchar_t.

The same applies to the string types defined by windows.h: LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.

Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

Difference between wait and sleep

wait() with a timeout value can wakeup upon timeout value elapsed or notify whichever is earlier (or interrupt as well), whereas, a sleep() wakes up on timeout value elapsed or interrupt whichever is earlier. wait() with no timeout value will wait for ever until notified or interrupted.

What is the difference between user and kernel modes in operating systems?

What

Basically the difference between kernel and user modes is not OS dependent and is achieved only by restricting some instructions to be run only in kernel mode by means of hardware design. All other purposes like memory protection can be done only by that restriction.

How

It means that the processor lives in either the kernel mode or in the user mode. Using some mechanisms the architecture can guarantee that whenever it is switched to the kernel mode the OS code is fetched to be run.

Why

Having this hardware infrastructure these could be achieved in common OSes:

  • Protecting user programs from accessing whole the memory, to not let programs overwrite the OS for example,
  • preventing user programs from performing sensitive instructions such as those that change CPU memory pointer bounds, to not let programs break their memory bounds for example.

Setting WPF image source in code

After having the same problem as you and doing some reading, I discovered the solution - Pack URIs.

I did the following in code:

Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;

Or shorter, by using another BitmapImage constructor:

finalImage.Source = new BitmapImage(
    new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));

The URI is broken out into parts:

  • Authority: application:///
  • Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path

    • AssemblyShortName: the short name for the referenced assembly.
    • ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;component: specifies that the assembly being referred to is referenced from the local assembly.
    • /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.

The three slashes after application: have to be replaced with commas:

Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details.

And of course, make sure you set the build action on your image to Resource.

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

Find maximum value of a column and return the corresponding row values using Pandas

My solution for finding maximum values in columns:

df.ix[df.idxmax()]

, also minimum:

df.ix[df.idxmin()]

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I had the same problem and the issue was that my child component had an @input named formControl.

So I just needed to change from:

<my-component [formControl]="formControl"><my-component/>

to:

<my-component [control]="control"><my-component/>

ts:

@Input()
control:FormControl;

How do I list all remote branches in Git 1.7+?

Using this command,

git log -r --oneline --no-merges --simplify-by-decoration --pretty=format:"%n %Cred CommitID %Creset: %h %n %Cred Remote Branch %Creset :%d %n %Cred Commit Message %Creset: %s %n"

CommitID       : 27385d919
Remote Branch  : (origin/ALPHA)
Commit Message :  New branch created

It lists all remote branches including commit messages and commit IDs that are referred to by remote branches.

Difference between setUp() and setUpBeforeClass()

setUpBeforeClass is run before any method execution right after the constructor (run only once)

setUp is run before each method execution

tearDown is run after each method execution

tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)

VueJs get url query

Current route properties are present in this.$route, this.$router is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query

$_POST not working. "Notice: Undefined index: username..."

You should check if the POST['username'] is defined. Use this above:

$username = "";

if(isset($_POST['username'])){
    $username = $_POST['username'];
}

"SELECT password FROM users WHERE username='".$username."'"

Copy multiple files with Ansible

Or you can use with_items:

- copy:
    src: "{{ item }}"
    dest: /etc/fooapp/
    owner: root
    mode: 600
  with_items:
    - dest_dir

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

I have debian 9 and to fix this i used the new library as follows:

ln -s /usr/bin/gpgv /usr/bin/gnupg2

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

Drop-down box dependent on the option selected in another drop-down box

In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

[Edit 2021] or use data-attributes, something like:

_x000D_
_x000D_
document.addEventListener("change", checkSelect);

function checkSelect(evt) {
  const origin = evt.target;

  if (origin.dataset.dependentSelector) {
    const selectedOptFrom = origin.querySelector("option:checked")
      .dataset.dependentOpt || "n/a";
    const addRemove = optData => (optData || "") === selectedOptFrom 
      ? "add" : "remove";
    document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
      .forEach( opt => 
        opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
  }
}
_x000D_
[data-from-dependent] {
  display: none;
}

[data-from-dependent].display {
  display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
  <option>MANUAL</option>
  <option data-dependent-opt="ONLINE">ONLINE</option>
  <option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>

<select id="status" name="status">
  <option>OPEN</option>
  <option>DELIVERED</option>
  <option data-from-dependent="ONLINE">SHIPPED</option>
  <option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
  <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
_x000D_
_x000D_

How to convert DateTime? to DateTime

You want to use the null-coalescing operator, which is designed for exactly this purpose.

Using it you end up with this code.

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

how to output every line in a file python

You probably want something like:

if data.find('!masters') != -1:
     f = open('masters.txt')
     lines = f.read().splitlines()
     f.close()
     for line in lines:
         print line
         sck.send('PRIVMSG ' + chan + " " + str(line) + '\r\n')

Don't close it every iteration of the loop and print line instead of lines. Also use readlines to get all the lines.

EDIT removed my other answer - the other one in this discussion is a better alternative than what I had, so there's no reason to copy it.

Also stripped off the \n with read().splitlines()

Ways to save enums in database

I would argue that the only safe mechanism here is to use the String name() value. When writing to the DB, you could use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without "imposing" this on the DB.

Output data from all columns in a dataframe in pandas

There is too much data to be displayed on the screen, therefore a summary is displayed instead.

If you want to output the data anyway (it won't probably fit on a screen and does not look very well):

print paramdata.values

converts the dataframe to its numpy-array matrix representation.

paramdata.columns

stores the respective column names and

paramdata.index

stores the respective index (row names).

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

Java rounding up to an int using Math.ceil

In Java adding a .0 will make it a double...

int total = (int) Math.ceil(157.0 / 32.0);

android: stretch image in imageview to fit screen

for XML android

android:src="@drawable/foto1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"

List all files from a directory recursively with Java

Just so you know isDirectory() is quite a slow method. I'm finding it quite slow in my file browser. I'll be looking into a library to replace it with native code.

How to make rounded percentages add up to 100%

You could try keeping track of your error due to rounding, and then rounding against the grain if the accumulated error is greater than the fractional portion of the current number.

13.62 -> 14 (+.38)
47.98 -> 48 (+.02 (+.40 total))
 9.59 -> 10 (+.41 (+.81 total))
28.78 -> 28 (round down because .81 > .78)
------------
        100

Not sure if this would work in general, but it seems to work similar if the order is reversed:

28.78 -> 29 (+.22)
 9.59 ->  9 (-.37; rounded down because .59 > .22)
47.98 -> 48 (-.35)
13.62 -> 14 (+.03)
------------
        100

I'm sure there are edge cases where this might break down, but any approach is going to be at least somewhat arbitrary since you're basically modifying your input data.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

For this purpose and if i dont have boolean variable i use the following:

<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

Tokenizing strings in C

Here is another strtok() implementation, which has the ability to recognize consecutive delimiters (standard library's strtok() does not have this)

The function is a part of BSD licensed string library, called zString. You are more than welcome to contribute :)

https://github.com/fnoyanisi/zString

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

As mentioned in previous posts, since strtok(), or the one I implmented above, relies on a static *char variable to preserve the location of last delimiter between consecutive calls, extra care should be taken while dealing with multi-threaded aplications.

Convert a string into an int

This is the simple solution for converting string to int

NSString *strNum = @"10";
int num = [strNum intValue];

but when you are getting value from the textfield then,

int num = [txtField.text intValue];

where txtField is an outlet of UITextField

In AVD emulator how to see sdcard folder? and Install apk to AVD?

These days the location of the emulated SD card is at /storage/emulated/0

List comprehension vs map

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

An example of the tiny speed advantage of map when using exactly the same function:

$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop

An example of how performance comparison gets completely reversed when map needs a lambda:

$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop

Run a single migration file

If you want to run a specific migration, do

$ rake db:migrate:up VERSION=20080906120000

If you want to run migrations multiple times, do

# use the STEP parameter if you need to go more than one version back
$ rake db:migrate:redo STEP=3

If you want to run a single migration multiple times, do

# this is super useful
$ rake db:migrate:redo VERSION=20080906120000

(you can find the version number in the filename of your migration)


Edit: You can also simply rename your migration file, Eg:

20151013131830_my_migration.rb -> 20151013131831_my_migration.rb

Then migrate normally, this will treat the migration as a new one (usefull if you want to migrate on a remote environment (such as staging) on which you have less control.

Edit 2: You can also just nuke the migration entry in the database. Eg:

rails_c> q = "delete from schema_migrations where version = '20151013131830'"
rails_c> ActiveRecord::Base.connection.execute(q)

rake db:migrate will then rerun the up method of the nuked migrations.

How to make for loops in Java increase by increments other than 1

Simply try this

for(int i=0; i<5; i=i+2){//value increased by 2
//body
}

OR

for(int i=0; i<5; i+=2){//value increased by 2
//body
}

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

What is the best way to update the entity in JPA

It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.

Real differences between "java -server" and "java -client"?

IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.

Edit to add: Here's some info from Sun, it's not very specific but will give you some ideas.

How do you count the lines of code in a Visual Studio solution?

Here's an update for Visual Studio 2012/2013/2015 for those who want to do the "Find" option (which I find to be the easiest): This RegEx will find all non-blank lines with several exclusions to give the most accurate results.

Enter the following RegEx into the "Find" box. Please make sure to select the "Use Regular Expressions" option. Change the search option to either "Current Project" or "Entire Solution" depending on your needs. Now select "Find All". At the bottom of the Find Results window, you will see "Matching Lines" which is the lines of code count.


^(?!(\s*\*))(?!(\s*\-\-\>))(?!(\s*\<\!\-\-))(?!(\s*\n))(?!(\s*\*\/))(?!(\s*\/\*))(?!(\s*\/\/\/))(?!(\s*\/\/))(?!(\s*\}))(?!(\s*\{))(?!(\s(using))).*$

This RegEx excludes the following items:


Comments

// This is a comment

Multi-Line comments (assuming the lines are correctly commented with a * in front of each line)

/* I am a
* multi-line
* comment */

XML for Intellisense

/// <summary>
/// I'm a class description for Intellisense
/// </summary>

HTML Comments:

<!-- I am a HTML Comment -->

Using statements:

using System;
using System.Web;

Opening curly braces:

{

Closing curly braces:

}

Note: anything between the braces would be included in the search, but in this example only 4 lines of code would count, instead of 18 actual non-blank lines:

        public class Test
        {
            /// <summary>
            /// Do Stuff
            /// </summary>
            public Test()
            {
                TestMe();
            }
            public void TestMe()
            {
                //Do Stuff Here
                /* And
                 * Do
                 * Stuff
                 * Here */
            }
        }

I created this to give me a much more accurate LOC count than some previous options, and figured I would share. The bosses love LOC counts, so I'm stuck with it for a while. I hope someone else can find this helpful, let me know if you have any questions or need help getting it to work.

Easiest way to copy a table from one database to another?

create table destination_customer like sakila.customer(Database_name.tablename), this will only copy the structure of the source table, for data also to get copied with the structure do this create table destination_customer as select * from sakila.customer

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

How to fix "Referenced assembly does not have a strong name" error?

There is a NuGet package named StrongNamer by Daniel Plaisted that seems to do the trick.

Is the simplest solution that I've found so far.

There are also a number of other NuGet packages to fix the strong naming problem such as Brutal.Dev.StrongNameSigner by Werner van Deventer, but I have not tested that one or any of the others.

How to use relative/absolute paths in css URLs?

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

What is the function __construct used for?

I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.

class_cat.php

class cat {
    function speak() {
        return "meow";  
    }
}

somepage.php

include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;

Where in @Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.

In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.

Where is the IIS Express configuration / metabase file found?

The configuration file is called applicationhost.config. It's stored here:

My Documents > IIS Express > config

usually, but not always, one of these paths will work

%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config

Update for VS2019
If you're using Visual Studio 2019+ check this path:

$(solutionDir)\.vs\{projectName}\config\applicationhost.config

Update for VS2015 (credit: @Talon)
If you're using Visual Studio 2015-2017 check this path:

$(solutionDir)\.vs\config\applicationhost.config

In Visual Studio 2015+ you can also configure which applicationhost.config file is used by altering the <UseGlobalApplicationHostFile>true|false</UseGlobalApplicationHostFile> setting in the project file (eg: MyProject.csproj). (source: MSDN forum)

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Lets try thinking outside of the box with/by logic and understand clearly these three interfaces in your question:

When the class of some instance implements the System.Collection.IEnumerable interface then, in simple words, we can say that this instance is both enumerable and iterable, which means that this instance allows somehow in a single loop to go/get/pass/traverse/iterate over/through all the items and elements that this instance contains.

This means that this is also possible to enumerate all the items and elements that this instance contains.

Every class that implements the System.Collection.IEnumerable interface also implements the GetEnumerator method that takes no arguments and returns an System.Collections.IEnumerator instance.

Instances of System.Collections.IEnumerator interface behaves very similar to C++ iterators.

When the class of some instance implements the System.Collection.ICollection interface then, in simple words, we can say that this instance is some collection of things.

The generic version of this interface, i.e. System.Collection.Generic.ICollection, is more informative because this generic interface explicitly states what is the type of the things in the collection.

This is all reasonable, rational, logical and makes sense that System.Collections.ICollection interface inherits from System.Collections.IEnumerable interface, because theoretically every collection is also both enumerable and iterable and this is theoretically possible to go over all the items and elements in every collection.

System.Collections.ICollection interface represents a finite dynamic collection that are changeable, which means that exist items can be removed from the collection and new items can be added to the same collection.

This explains why System.Collections.ICollection interface has the "Add" and "Remove" methods.

Because that instances of System.Collections.ICollection interface are finite collections then the word "finite" implies that every collection of this interface always has a finite number of items and elements in it.

The property Count of System.Collections.ICollection interface supposes to return this number.

System.Collections.IEnumerable interface does not have these methods and properties that System.Collections.ICollection interface has, because it does not make any sense that System.Collections.IEnumerable will have these methods and properties that System.Collections.ICollection interface has.

The logic also says that every instance that is both enumerable and iterable is not necessarily a collection and not necessarily changeable.

When I say changeable, I mean that don't immediately think that you can add or remove something from something that is both enumerable and iterable.

If I just created some finite sequence of prime numbers, for example, this finite sequence of prime numbers is indeed an instance of System.Collections.IEnumerable interface, because now I can go over all the prime numbers in this finite sequence in a single loop and do whatever I want to do with each of them, like printing each of them to the console window or screen, but this finite sequence of prime numbers is not an instance of System.Collections.ICollection interface, because this is not making sense to add composite numbers to this finite sequence of prime numbers.

Also you want in the next iteration to get the next closest larger prime number to the current prime number in the current iteration, if so you also don't want to remove exist prime numbers from this finite sequence of prime numbers.

Also you probably want to use, code and write "yield return" in the GetEnumerator method of the System.Collections.IEnumerable interface to produce the prime numbers and not allocating anything on the memory heap and then task the Garbage Collector (GC) to both deallocate and free this memory from the heap, because this is obviously both waste of operating system memory and decreases performance.

Dynamic memory allocation and deallocation on the heap should be done when invoking the methods and properties of System.Collections.ICollection interface, but not when invoking the methods and properties of System.Collections.IEnumerable interface (although System.Collections.IEnumerable interface has only 1 method and 0 properties).

According to what others said in this Stack Overflow webpage, System.Collections.IList interface simply represents an orderable collection and this explains why the methods of System.Collections.IList interface work with indexes in contrast to these of System.Collections.ICollection interface.

In short System.Collections.ICollection interface does not imply that an instance of it is orderable, but System.Collections.IList interface does imply that.

Theoretically ordered set is special case of unordered set.

This also makes sense and explains why System.Collections.IList interface inherits System.Collections.ICollection interface.

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

Can I multiply strings in Java to repeat sequences?

I don't believe Java natively provides this feature, although it would be nice. I write Perl code occasionally and the x operator in Perl comes in really handy for repeating strings!

However StringUtils in commons-lang provides this feature. The method is called repeat(). Your only other option is to build it manually using a loop.

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

Leader Not Available Kafka in Console Producer

This below line I have added in config/server.properties, that resolved my issue similar above issue. Hope this helps, its pretty much well documented in server.properties file, try to read and understand before you modify this. advertised.listeners=PLAINTEXT://<your_kafka_server_ip>:9092

Windows path in Python

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join ...

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. ... or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Converting ArrayList to Array in java

This can be done using stream:

List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
    List<String[]> objects = stringList.stream()
                                       .map(s -> s.split("#"))
                                       .collect(Collectors.toList());

The return value would be arrays of split string. This avoids converting the arraylist to an array and performing the operation.

What does "\r" do in the following script?

Actually, this has nothing to do with the usual Windows / Unix \r\n vs \n issue. The TELNET procotol itself defines \r\n as the end-of-line sequence, independently of the operating system. See RFC854.

Hide Twitter Bootstrap nav collapse on click

In most cases you will only want to call the toggle function if the toggle button is visible...

if ($('.navbar-toggler').is(":visible")) $('.navbar-toggler').click();

Revert a jQuery draggable object back to its original container on out event of droppable

I've found another easy way to deal with this problem, you just need the attribute " connectToSortable:" to draggable like as below code:

$("#a1,#a2").draggable({
        connectToSortable: "#b,#a",
        revert: 'invalid',
    });

PS: More detail and example
How to move Draggable objects between source area and target area with jQuery

Access Enum value using EL with JSTL

A simple comparison against string works:

<c:when test="${someModel.status == 'OLD'}">

Copy table without copying data

Try

CREATE TABLE foo LIKE bar;

so the keys and indexes are copied over as, well.

Documentation

Writing Python lists to columns in csv

change them to rows

rows = zip(list1,list2,list3,list4,list5)

then just

import csv

with open(newfilePath, "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

HTML checkbox - allow to check only one checkbox

$('#OvernightOnshore').click(function () {
    if ($('#OvernightOnshore').prop("checked") == true) {
        if ($('#OvernightOffshore').prop("checked") == true) {
            $('#OvernightOffshore').attr('checked', false)
        }
    }
})

$('#OvernightOffshore').click(function () {
    if ($('#OvernightOffshore').prop("checked") == true) {
        if ($('#OvernightOnshore').prop("checked") == true) {
            $('#OvernightOnshore').attr('checked', false);
        }
    }
})

This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

How can I put a database under git (version control)?

  • Irmin
  • Flur.ee
  • Crux DB
  • TerminusDB

I have been looking for the same feature for Postgres (or SQL databases in general) for a while, but I found no tools to be suitable (simple and intuitive) enough. This is probably due to the binary nature of how data is stored. Klonio sounds ideal but looks dead. Noms DB looks interesting (and alive). Also take a look at Irmin (OCaml-based with Git-properties).

Though this doesn't answer the question in that it would work with Postgres, check out the Flur.ee database. It has a "time-travel" feature that allows you to query the data from an arbitrary point in time. I'm guessing it should be able to work with a "branching" model.

This database was recently being developed for blockchain-purposes. Due to the nature of blockchains, the data needs to be recorded in increments, which is exactly how git works. They are targeting an open-source release in Q2 2019.

Because each Fluree database is a blockchain, it stores the entire history of every transaction performed. This is part of how a blockchain ensures that information is immutable and secure.

Update: Also check out the Crux database, which can query across the time dimension of inserts, which you could see as 'versions'. Crux seems to be an open-source implementation of the highly appraised Datomic.

Crux is a bitemporal database that stores transaction time and valid time histories. While a [uni]temporal database enables "time travel" querying through the transactional sequence of database states from the moment of database creation to its current state, Crux also provides "time travel" querying for a discrete valid time axis without unnecessary design complexity or performance impact. This means a Crux user can populate the database with past and future information regardless of the order in which the information arrives, and make corrections to past recordings to build an ever-improving temporal model of a given domain.

Update II Check out Terminus DB: "Documentation for TerminusDB - an open-source graph database that stores data like git".

Operator overloading in Java

One can try Java Operator Overloading. It has its own limitations, but it worth trying if you really want to use operator overloading.

Getting number of days in a month

Use System.DateTime.DaysInMonth, from code sample:

const int July = 7;
const int Feb = 2;

// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);

// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);

// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

For Kotlin Users don't forget to add ? in data: Intent? like

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

Server did not recognize the value of HTTP Header SOAPAction

Just to help someone on this problem, after an afternoon of debug, the problem was that the web service was developed with framework 4.5 and the call from android must be done with SoapEnvelope.VER12 and not with SoapEnvelope.VER11

Git - remote: Repository not found

I solved it by deleting the .git file (hidden folder) and then uploading it again.

How to select the first, second, or third element with a given class name?

This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.

I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type which, for my situation, worked. (So, thanks for that, @Bdwey.)

I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.

Turns out as follows: div.myclass:nth-of-type(2) does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening divs between your div.myclass instances.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

_x000D_
_x000D_
div {_x000D_
  margin-bottom: 2em;_x000D_
  border: red solid 1px;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-size: 12pt;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
  background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
  background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
  <h1 class="A">h1.A #1</h1>_x000D_
  <h1 class="A">h1.A #2</h1>_x000D_
  <h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h2 class="A">h2.A #1</h2>_x000D_
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
  <h2 class="A">h2.A #2</h2>_x000D_
  <h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h3 class="A">h3.A #1</h3>_x000D_
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
  <h3 class="A">h3.A #2</h3>_x000D_
  <h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Make Div Draggable using CSS

Only using css techniques this does not seem possible to me. But you could use jqueryui draggable:

$('#drag_me').draggable();

jQuery Ajax Request inside Ajax Request

Here is an example:

$.ajax({
        type: "post",
        url: "ajax/example.php",
        data: 'page=' + btn_page,
        success: function (data) {
            var a = data; // This line shows error.
            $.ajax({
                type: "post",
                url: "example.php",
                data: 'page=' + a,
                success: function (data) {

                }
            });
        }
    });

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

Can Mockito stub a method without regard to the argument?

http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html

anyObject() should fit your needs.

Also, you can always consider implementing hashCode() and equals() for the Bazoo class. This would make your code example work the way you want.

How to convert a Django QuerySet to a list

By the use of slice operator with step parameter which would cause evaluation of the queryset and create a list.

list_of_answers = answers[::1]

or initially you could have done:

answers = Answer.objects.filter(id__in=[answer.id for answer in
        answer_set.answers.all()])[::1]

How to create a <style> tag with Javascript?

I'm assuming that you're wanting to insert a style tag versus a link tag (referencing an external CSS), so that's what the following example does:

<html>
 <head>
  <title>Example Page</title>
 </head>
 <body>
  <span>
   This is styled dynamically via JavaScript.
  </span>
 </body>
 <script type="text/javascript">
   var styleNode = document.createElement('style');
   styleNode.type = "text/css";
   // browser detection (based on prototype.js)
   if(!!(window.attachEvent && !window.opera)) {
        styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
   } else {
        var styleText = document.createTextNode('span { color: rgb(255, 0, 0); } ');
        styleNode.appendChild(styleText);
   }
   document.getElementsByTagName('head')[0].appendChild(styleNode);
 </script>
</html>

Also, I noticed in your question that you are using innerHTML. This is actually a non-standard way of inserting data into a page. The best practice is to create a text node and append it to another element node.

With respect to your final question, you're going to hear some people say that your work should work across all of the browsers. It all depends on your audience. If no one in your audience is using Chrome, then don't sweat it; however, if you're looking to reach the biggest audience possible, then it's best to support all major A-grade browsers

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

dll missing in JDBC

Friends I had the same problem because of the different bit version Make sure following point * Your jdk bit 64 or 32 * Your Path for sqljdbc_4.0\enu\auth\x64 or x86 this directory depend on your jdk bit * sqljdbc_auth.dll select this file based on your bit x64 or x86 and put this in system32 folder and it will works for me

What does Ruby have that Python doesn't, and vice versa?

python has named optional arguments

def func(a, b=2, c=3):
    print a, b, c

>>> func(1)
1 2 3
>>> func(1, c=4)
1 2 4

AFAIK Ruby has only positioned arguments because b=2 in the function declaration is an affectation that always append.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

If you will apply security="none" then no csrf token will be generated. The page will not pass through security filter. Use role ANONYMOUS.

I have not gone in details, but it is working for me.

 <http auto-config="true" use-expressions="true">
   <intercept-url pattern="/login.jsp" access="hasRole('ANONYMOUS')" />
   <!-- you configuration -->
   </http>

Notice: Undefined variable: _SESSION in "" on line 9

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");

Omitting the first line from any Linux command output

ls -lart | tail -n +2 #argument means starting with line 2

Reset all the items in a form

Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.

 public static void ClearControl(Control control)
        {
            if (control is TextBox)
            {
                TextBox txtbox = (TextBox)control;
                txtbox.Text = string.Empty;
            }
            else if (control is CheckBox)
            {
                CheckBox chkbox = (CheckBox)control;
                chkbox.Checked = false;
            }
            else if (control is RadioButton)
            {
                RadioButton rdbtn = (RadioButton)control;
                rdbtn.Checked = false;
            }
            else if (control is DateTimePicker)
            {
                DateTimePicker dtp = (DateTimePicker)control;
                dtp.Value = DateTime.Now;
            }
            else if (control is ComboBox)
            {
                ComboBox cmb = (ComboBox)control;
                if (cmb.DataSource != null)
                {
                    cmb.SelectedItem = string.Empty;
                    cmb.SelectedValue = 0;
                }
            }
            ClearErrors(control);
            // repeat for combobox, listbox, checkbox and any other controls you want to clear
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    ClearControl(child);
                }
            }


        }

Select row on click react-table

Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:

  return (
    <li key={move}>
      <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );

Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

How to compile a 64-bit application using Visual C++ 2010 Express?

And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.

How to log SQL statements in Spring Boot?

Translated accepted answer to YAML works for me

logging:
  level:
    org:
      hibernate:
        SQL:
          TRACE
        type:
          descriptor:
            sql:
              BasicBinder:
                TRACE

What is the difference between HTML tags and elements?

http://html.net/tutorials/html/lesson3.php

Tags are labels you use to mark up the begining and end of an element.

All tags have the same format: they begin with a less-than sign "<" and end with a greater-than sign ">".

Generally speaking, there are two kinds of tags - opening tags: <html> and closing tags: </html>. The only difference between an opening tag and a closing tag is the forward slash "/". You label content by putting it between an opening tag and a closing tag.

HTML is all about elements. To learn HTML is to learn and use different tags.

For example:

<h1></h1>

Where as elements are something that consists of start tag and end tag as shown:

<h1>Heading</h1>

Angular 5 ngHide ngShow [hidden] not working

If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none

Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:

enter image description here

If you found display of [hidden] class is overridden, you need to add this css code to your style:

[hidden] {
    display: none !important;
}

CMake: How to build external projects and include their targets

I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.

"CMakeLists.txt"

cmake_minimum_required(VERSION 3.10.2)

# Target Project
project (ClientProgram)

# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers


# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables


# This Project Depends on External Project(s) 
include (ExternalProject)

# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX          ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL             http://myproject.com/MyLibrary.tgz
URL_HASH        SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server

# Begin: Download Source from GIT Repository
#    GIT_REPOSITORY  https://github.com/<project>.git
#    GIT_TAG         <Refer github.com releases -> Tags>
#    GIT_SHALLOW     ON
# End: Download Source from GIT Repository

# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS      -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS      -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments    
)

# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory

# Acquire Installation Directory of 
ExternalProject_Get_Property (${libTLS} install_dir)

# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)

# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)

# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library

# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component

# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)

COALESCE Function in TSQL

I've been told that COALESCE is less costly than ISNULL, but research doesn't indicate that. ISNULL takes only two parameters, the field being evaluated for NULL, and the result you want if it is evaluated as NULL. COALESCE will take any number of parameters, and return the first value encountered that isn't NULL.

There's a much more thorough description of the details here http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

Java string to date conversion

You can use SimpleDateformat for change string to date

_x000D_
_x000D_
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2000-01-01";
Date date = sdf.parse(strDate);
_x000D_
_x000D_
_x000D_

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

Example of a strong and weak entity types

A weak entity is the entity which can't be fully identified by its own attributes and takes the foreign key as an attribute (generally it takes the primary key of the entity it is related to) in conjunction.

Examples

The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel.
Another example is the
bank account of a particular bank has no existence if the bank doesn't exist anymore.

How to set time to midnight for current day?

I believe you are looking for DateTime.Today. The documentation states:

An object that is set to today's date, with the time component set to 00:00:00.

http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

Your code would be

DateTime _Begin = DateTime.Today;

Single vs Double quotes (' vs ")

I'm newbie here but I use single quote mark only when I use double quote mark inside the first one. If I'm not clear I show You example:

<p align="center" title='One quote mark at the beginning so now I can
"cite".'> ... </p>

I hope I helped.

Multidimensional Lists in C#

You should use List<Person> or a HashSet<Person>.

Alter column, add default constraint

alter table TableName drop constraint DF_TableName_WhenEntered

alter table TableName add constraint DF_TableName_WhenEntered default getutcdate() for WhenEntered

Where does one get the "sys/socket.h" header/source file?

Given that Windows has no sys/socket.h, you might consider just doing something like this:

#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif

I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a

#ifdef __WIN32__
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   WSAStartup(versionWanted, &wsaData);
#endif

at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.

What is SYSNAME data type in SQL Server?

Let me list a use case below. Hope it helps. Here I'm trying to find the Table Owner of the Table 'Stud_dtls' from the DB 'Students'. As Mikael mentioned, sysname could be used when there is a need for creating some dynamic sql which needs variables holding table names, column names and server names. Just thought of providing a simple example to supplement his point.

USE Students

DECLARE @TABLE_NAME sysname

SELECT @TABLE_NAME = 'Stud_dtls'

SELECT TABLE_SCHEMA 
  FROM INFORMATION_SCHEMA.Tables
 WHERE TABLE_NAME = @TABLE_NAME

How to get a property value based on the name

return car.GetType().GetProperty(propertyName).GetValue(car, null);

Entity Framework Migrations renaming tables and columns

If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn code which is required:

Step One Use the ColumnAttribute to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged)

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Group_Id{get;set}
}

Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force) in the Package Manager Console

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Section_Id{get;set}
}

If you look at the Migration class you can see the automatically code generated is RenameColumn.

Merge up to a specific commit

Run below command into the current branch folder to merge from this <commit-id> to current branch, --no-commit do not make a new commit automatically

git merge --no-commit <commit-id>

git merge --continue can only be run after the merge has resulted in conflicts.

git merge --abort Abort the current conflict resolution process, and try to reconstruct the pre-merge state.

How to get maximum value from the Collection (for example ArrayList)?

package in.co.largestinarraylist;

import java.util.ArrayList;
import java.util.Scanner;

public class LargestInArrayList {

    public static void main(String[] args) {

        int n;
        ArrayList<Integer> L = new ArrayList<Integer>();
        int max;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Size of Array List");
        n = in.nextInt();
        System.out.println("Enter elements in Array List");

        for (int i = 0; i < n; i++) {
            L.add(in.nextInt());
        }

        max = L.get(0);

        for (int i = 0; i < L.size(); i++) {
            if (L.get(i) > max) {
                max = L.get(i);
            }
        }

        System.out.println("Max Element: " + max);
        in.close();
    }
}

Difference Between One-to-Many, Many-to-One and Many-to-Many?

Looks like everyone is answering One-to-many vs. Many-to-many:

The difference between One-to-many, Many-to-one and Many-to-Many is:

One-to-many vs Many-to-one is a matter of perspective. Unidirectional vs Bidirectional will not affect the mapping but will make difference on how you can access your data.

  • In Many-to-one the many side will keep reference of the one side. A good example is "A State has Cities". In this case State is the one side and City is the many side. There will be a column state_id in the table cities.

In unidirectional, Person class will have List<Skill> skills but Skill will not have Person person. In bidirectional, both properties are added and it allows you to access a Person given a skill( i.e. skill.person).

  • In One-to-Many the one side will be our point of reference. For example, "A User has Addresses". In this case we might have three columns address_1_id, address_2_id and address_3_id or a look up table with multi column unique constraint on user_id on address_id.

In unidirectional, a User will have Address address. Bidirectional will have an additional List<User> users in the Address class.

  • In Many-to-Many members of each party can hold reference to arbitrary number of members of the other party. To achieve this a look up table is used. Example for this is the relationship between doctors and patients. A doctor can have many patients and vice versa.

Retrieve a single file from a repository

Related to @Steven Penny's answer, I also use wget. Furthermore, to decide which file to send the output to I use -O .

If you are using gitlabs another possibility for the url is:

wget "https://git.labs.your-server/your-repo/raw/master/<path-to-file>" -O <output-file>

Unless you have the certificate or you access from a trusted server for the gitlabs installation you need --no-check-certificate as @Kos said. I prefer that rather than modifying .wgetrc but it depends on your needs.

If it is a big file you might consider using -c option with wget. To be able to continue downloading the file from where you left it if the previous intent failed in the middle.

How do you programmatically update query params in react-router?

    for react-router v4.3, 
 const addQuery = (key, value) => {
  let pathname = props.location.pathname; 
 // returns path: '/app/books'
  let searchParams = new URLSearchParams(props.location.search); 
 // returns the existing query string: '?type=fiction&author=fahid'
  searchParams.set(key, value);
  this.props.history.push({
           pathname: pathname,
           search: searchParams.toString()
     });
 };

  const removeQuery = (key) => {
  let pathname = props.location.pathname; 
 // returns path: '/app/books'
  let searchParams = new URLSearchParams(props.location.search); 
 // returns the existing query string: '?type=fiction&author=fahid'
  searchParams.delete(key);
  this.props.history.push({
           pathname: pathname,
           search: searchParams.toString()
     });
 };


 ```

 ```
 function SomeComponent({ location }) {
   return <div>
     <button onClick={ () => addQuery('book', 'react')}>search react books</button>
     <button onClick={ () => removeQuery('book')}>remove search</button>
   </div>;
 }
 ```


 //  To know more on URLSearchParams from 
[Mozilla:][1]

 var paramsString = "q=URLUtils.searchParams&topic=api";
 var searchParams = new URLSearchParams(paramsString);

 //Iterate the search parameters.
 for (let p of searchParams) {
   console.log(p);
 }

 searchParams.has("topic") === true; // true
 searchParams.get("topic") === "api"; // true
 searchParams.getAll("topic"); // ["api"]
 searchParams.get("foo") === null; // true
 searchParams.append("topic", "webdev");
 searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
 searchParams.set("topic", "More webdev");
 searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
 searchParams.delete("topic");
 searchParams.toString(); // "q=URLUtils.searchParams"


[1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

How to convert Calendar to java.sql.Date in Java?

Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))

Find the location of a character in string

You could use grep as well:

grep('2', strsplit(string, '')[[1]])
#4 24

AddTransient, AddScoped and AddSingleton Services Differences

In .NET's dependency injection there are three major lifetimes:

Singleton which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.

Scoped lifetime services are created once per request within the scope. It is equivalent to a singleton in the current scope. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.

Here you can find and examples to see the difference:

ASP.NET 5 MVC6 Dependency Injection in 6 Steps (web archive link due to dead link)

Your Dependency Injection ready ASP.NET : ASP.NET 5

And this is the link to the official documentation:

Dependency injection in ASP.NET Core

How do I launch a Git Bash window with particular working directory using a script?

This is the command which can be executed directly in Run dialog box (shortcut is win+R) and also works well saved as a .bat script:

cmd /c (start /d "/path/to/dir" bash --login) && exit

<button> background image

Replace button #rock With #rock

No need for additional selector scope. You're using an id which is as specific as you can be.

JsBin example: http://jsbin.com/idobar/1/edit

How to set an button align-right with Bootstrap?

This worked for me:

<div class="text-right">
    <button type="button">Button 1</button>
    <button type="button">Button 2</button>
</div>

How do I perform query filtering in django templates

I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.

Some other possible solutions:

  1. Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.

  2. Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.

HTTP Request in Swift with POST method

let session = URLSession.shared
        let url = "http://...."
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        var params :[String: Any]?
        params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
            let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                if let response = response {
                    let nsHTTPResponse = response as! HTTPURLResponse
                    let statusCode = nsHTTPResponse.statusCode
                    print ("status code = \(statusCode)")
                }
                if let error = error {
                    print ("\(error)")
                }
                if let data = data {
                    do{
                        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                        print ("data = \(jsonResponse)")
                    }catch _ {
                        print ("OOps not good JSON formatted response")
                    }
                }
            })
            task.resume()
        }catch _ {
            print ("Oops something happened buddy")
        }

Not able to start Genymotion device

Here is a trick i use. Go to http://androvm.org/blog/download/ and download the latest AndroidVm.

Genymotion is the extention of AndroidVM.

How can I export Excel files using JavaScript?

Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.

Your user will then be presented with the CSV download link.

How can I find the number of years between two dates?

import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || 
        (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

The real difference between "int" and "unsigned int"

The internal representation of int and unsigned int is the same.

Therefore, when you pass the same format string to printf it will be printed as the same.

However, there are differences when you compare them. Consider:

int x = 0x7FFFFFFF;
int y = 0xFFFFFFFF;
x < y // false
x > y // true
(unsigned int) x < (unsigned int y) // true
(unsigned int) x > (unsigned int y) // false

This can be also a caveat, because when comparing signed and unsigned integer one of them will be implicitly casted to match the types.

How to select/get drop down option in Selenium 2

A similar option to what was posted above by janderson would be so simply use the .GetAttribute method in selenium 2. Using this, you can grab any item that has a specific value or label that you are looking for. This can be used to determine if an element has a label, style, value, etc. A common way to do this is to loop through the items in the drop down until you find the one that you want and select it. In C#

int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count(); 
for(int i = 1; i <= items; i++)
{
    string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
    if(value.Conatains("Label_I_am_Looking_for"))
    {
        driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click(); 
        //Clicked on the index of the that has your label / value
    }
}

Spring @Value is not resolving to value from property file

Have a read of pedjaradenkovic's comment.

Further to the link he provides, the reason this isn't working is that @Value processing requires a PropertySourcesPlaceholderConfigurer instead of a PropertyPlaceholderConfigurer.

Awk if else issues

You forgot braces around the if block, and a semicolon between the statements in the block.

awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

Can I create a One-Time-Use Function in a Script or Stored Procedure?

The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:

IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
    SELECT Division =
        CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND  @Numerator != 0 AND @Numerator is NOT NULL THEN
        @Numerator / @Denominator
        ELSE
            0
        END
    RETURN
END
GO

Exec ##fn_Divide 6,4

This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.

Convert character to ASCII numeric value in java

Instead of this:

String char = name.substring(0,1); //char="a"

You should use the charAt() method.

char c = name.charAt(0); // c='a'
int ascii = (int)c;

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

How to check if a variable is set in Bash?

The answers above do not work when Bash option set -u is enabled. Also, they are not dynamic, e.g., how to test is variable with name "dummy" is defined? Try this:

is_var_defined()
{
    if [ $# -ne 1 ]
    then
        echo "Expected exactly one argument: variable name as string, e.g., 'my_var'"
        exit 1
    fi
    # Tricky.  Since Bash option 'set -u' may be enabled, we cannot directly test if a variable
    # is defined with this construct: [ ! -z "$var" ].  Instead, we must use default value
    # substitution with this construct: [ ! -z "${var:-}" ].  Normally, a default value follows the
    # operator ':-', but here we leave it blank for empty (null) string.  Finally, we need to
    # substitute the text from $1 as 'var'.  This is not allowed directly in Bash with this
    # construct: [ ! -z "${$1:-}" ].  We need to use indirection with eval operator.
    # Example: $1="var"
    # Expansion for eval operator: "[ ! -z \${$1:-} ]" -> "[ ! -z \${var:-} ]"
    # Code  execute: [ ! -z ${var:-} ]
    eval "[ ! -z \${$1:-} ]"
    return $?  # Pedantic.
}

Related: In Bash, how do I test if a variable is defined in "-u" mode

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

Lua - Current time in milliseconds

If you're using OpenResty then it provides for in-built millisecond time accuracy through the use of its ngx.now() function. Although if you want fine grained millisecond accuracy then you may need to call ngx.update_time() first. Or if you want to go one step further...

If you are using luajit enabled environment, such as OpenResty, then you can also use ffi to access C based time functions such as gettimeofday() e.g: (Note: The pcall check for the existence of struct timeval is only necessary if you're running it repeatedly e.g. via content_by_lua_file in OpenResty - without it you run into errors such as attempt to redefine 'timeval')

if pcall(ffi.typeof, "struct timeval") then
        -- check if already defined.
else
        -- undefined! let's define it!
        ffi.cdef[[
           typedef struct timeval {
                long tv_sec;
                long tv_usec;
           } timeval;

        int gettimeofday(struct timeval* t, void* tzp);
]]
end
local gettimeofday_struct = ffi.new("struct timeval")
local function gettimeofday()
        ffi.C.gettimeofday(gettimeofday_struct, nil)
        return tonumber(gettimeofday_struct.tv_sec) * 1000000 + tonumber(gettimeofday_struct.tv_usec)
end

Then the new lua gettimeofday() function can be called from lua to provide the clock time to microsecond level accuracy.

Indeed, one could take a similar approaching using clock_gettime() to obtain nanosecond accuracy.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

You can clone https://github.com/brock/node-reinstall and run the simple command as given in the repository.After that just restart your system.
This is the simplest method and also worked for me.

How do I pass a unique_ptr argument to a constructor or a function?

Edit: This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: How do I pass a unique_ptr argument to a constructor or a function?

The basic idea of ::std::move is that people who are passing you the unique_ptr should be using it to express the knowledge that they know the unique_ptr they're passing in will lose ownership.

This means you should be using an rvalue reference to a unique_ptr in your methods, not a unique_ptr itself. This won't work anyway because passing in a plain old unique_ptr would require making a copy, and that's explicitly forbidden in the interface for unique_ptr. Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use ::std::move inside your methods as well.

This means your two methods should look like this:

Base(Base::UPtr &&n) : next(::std::move(n)) {} // Spaces for readability

void setNext(Base::UPtr &&n) { next = ::std::move(n); }

Then people using the methods would do this:

Base::UPtr objptr{ new Base; }
Base::UPtr objptr2{ new Base; }
Base fred(::std::move(objptr)); // objptr now loses ownership
fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership

As you see, the ::std::move expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have objptr suddenly lose ownership for no readily apparent reason.

Printing Lists as Tabular Data

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
    print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

Https Connection Android

While trying to answer this question I found a better tutorial. With it you don't have to compromise the certificate check.

http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

*I did not write this but thanks to Bob Lee for the work

how to set start page in webconfig file in asp.net c#

If your project contains a RouteConfig.cs file, then you probably need to ignore the route to the root by adding routes.IgnoreRoute(""); in this file.

If it doen't solve your problem, try this :

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.AppRelativeCurrentExecutionFilePath == "~/")
        Response.Redirect("~/index.aspx");
}

Text Editor which shows \r\n?

EmEditor does this. You can also customize what symbols actually display to show them.

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

How to delete the first row of a dataframe in R?

You can use negative indexing to remove rows, e.g.:

dat <- dat[-1, ]

Here is an example:

> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
  A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
  A B
2 2 2
3 3 3

That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

How can I match a string with a regex in Bash?

shopt -s nocasematch

if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
 then exit 0 
fi

How to read barcodes with the camera on Android?

With Google Firebase ML Kit's barcode scanning API, you can read data encoded using most standard barcode formats.

https://firebase.google.com/docs/ml-kit/read-barcodes?authuser=0

You can follow this link to read barcodes efficiently.

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

How do I clear a search box with an 'x' in bootstrap 3?

Place the image (cancel icon) with position absolute, adjust top and left properties and call method onclick event which clears the input field.

<div class="form-control">
    <input type="text" id="inputField" />
</div>
<span id="iconSpan"><img src="icon.png" onclick="clearInputField()"/></span>

In css position the span accordingly,

#iconSpan {
 position : absolute;
 top:1%;
 left :14%;
}

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

PHP Converting Integer to Date, reverse of strtotime

Yes you can convert it back. You can try:

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

The logic behind this conversion from date to an integer is explained in strtotime in PHP:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

For example, strtotime("1970-01-01 00:00:00") gives you 0 and strtotime("1970-01-01 00:00:01") gives you 1.

This means that if you are printing strtotime("2014-01-01 00:00:01") which will give you output 1388516401, so the date 2014-01-01 00:00:01 is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.

Reference alias (calculated in SELECT) in WHERE clause

You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated. Two workarounds:

SELECT BalanceDue FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices
) AS x
WHERE BalanceDue > 0;

Or just repeat the expression:

SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE  (InvoiceTotal - PaymentTotal - CreditTotal)  > 0;

I prefer the latter. If the expression is extremely complex (or costly to calculate) you should probably consider a computed column (and perhaps persisted) instead, especially if a lot of queries refer to this same expression.

PS your fears seem unfounded. In this simple example at least, SQL Server is smart enough to only perform the calculation once, even though you've referenced it twice. Go ahead and compare the plans; you'll see they're identical. If you have a more complex case where you see the expression evaluated multiple times, please post the more complex query and the plans.

Here are 5 example queries that all yield the exact same execution plan:

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE LEN(name) + column_id > 30;

SELECT x FROM (
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE column_id + LEN(name) > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE LEN(name) + column_id > 30;

Resulting plan for all five queries:

enter image description here

How to run Tensorflow on CPU

Another possible solution on installation level would be to look for the CPU only variant: https://www.tensorflow.org/install/pip#package-location

In my case, this gives right now:

pip3 install https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.2.0-cp38-cp38-win_amd64.whl

Just select the correct version. Bonus points for using a venv like explained eg in this answer.

How can I specify the schema to run an sql file against in the Postgresql command line

I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.

After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:

CREATE TABLE "my_schema"."my_table" (...); COPY "my_schema"."my_table" (...) FROM stdin;

This way using psql -f xxxxx works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).

SQL Server copy all rows from one table into another i.e duplicate table

select * into x_history from your_table_here;
truncate table your_table_here;