Programs & Examples On #Centralized

How do I import a specific version of a package using go get?

Go 1.11 will have a feature called go modules and you can simply add a dependency with a version. Follow these steps:

go mod init .
go mod edit -require github.com/wilk/[email protected]
go get -v -t ./...   
go build
go install 

Here's more info on that topic - https://github.com/golang/go/wiki/Modules

Best practice for localization and globalization of strings and labels

jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.

to know more about this take a look at the How to internationalize your pages using JQuery?

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;

@Entity
public class Purchase {

    private Date date;

    @Column
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        // force java.sql.Timestamp to be set as a java.util.Date
        this.date = new Date(date.getTime());
    }

}

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

Java Swing - how to show a panel on top of another panel?

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

Am I understanding this question correctly?

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

I find it useful when including or requiring _dbconnection.php_ and _functions.php in files that are actually processed, rather than including in the header. Which is included in itself.

So if your header and footer is included, simply include all your functional files before the header is included.

Combine two (or more) PDF's

I know a lot of people have recommended PDF Sharp, however it doesn't look like that project has been updated since june of 2008. Further, source isn't available.

Personally, I've been playing with iTextSharp which has been pretty easy to work with.

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

how to show lines in common (reverse diff)?

Was asked here before: Unix command to find lines common in two files

You could also try with perl (credit goes here)

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

List comprehension vs map

I find list comprehensions are generally more expressive of what I'm trying to do than map - they both get it done, but the former saves the mental load of trying to understand what could be a complex lambda expression.

There's also an interview out there somewhere (I can't find it offhand) where Guido lists lambdas and the functional functions as the thing he most regrets about accepting into Python, so you could make the argument that they're un-Pythonic by virtue of that.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Angular EXCEPTION: No provider for Http

Add HttpModule to imports array in app.module.ts file before you use it.

_x000D_
_x000D_
import { HttpModule } from '@angular/http';_x000D_
_x000D_
@NgModule({_x000D_
  declarations: [_x000D_
    AppComponent,_x000D_
    CarsComponent_x000D_
  ],_x000D_
  imports: [_x000D_
    BrowserModule,_x000D_
 HttpModule  _x000D_
  ],_x000D_
  providers: [],_x000D_
  bootstrap: [AppComponent]_x000D_
})_x000D_
export class AppModule { }
_x000D_
_x000D_
_x000D_

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

How to convert array into comma separated string in javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

_x000D_
_x000D_
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
_x000D_
_x000D_

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

Java converting int to hex and back again

As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

Integer.toString(byte/integer, 16);

or

String.format("%02X", byte/integer);

reverse you can use

Integer.parseInt(hexString, 16);

Difference between nVidia Quadro and Geforce cards?

Hardware wise the Quadro and GeForce cards are often idential. Indeed it is sometimes possible to convert some models from GeForce into Quadro by simply uploading new firmware and changing a couple resistor jumpers.

The difference is in the intended market and hence cost.

Quadro cards are intended for CAD. High end CAD software still uses OpenGL, whereas games and lower end CAD software use Direct3D (aka DirectX).

Quadro cards simply have firmware that is optimised for OpenGL. In the early days OpenGL was better and faster than Direct3D but now there is little difference. Gaming cards only support a very limited set of OpenGL, hence they don't run it very well.

CAD companies, e.g. Dassault with SolidWorks actively push high end cards by offering no support for DirectX with any level of performance.

Other CAD companies such as Altium, with Altium Designer, made the decision that forcing their customers to buy more expensive cards is not worthwhile when Direct3D is as good (if not better these days) than OpenGL.

Because of the cost, there are often other differences in the hardware, such as less use of overclocking, more memory etc, but these have relatively minor effects compared with the firmware support.

About catching ANY exception

try:
    whatever()
except:
    # this will catch any exception or error

It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

Angular IE Caching issue for $http

Solution above will work (make the url unique by adding in the querystring a new param) but I prefer the solution propose [here]: Better Way to Prevent IE Cache in AngularJS?, which handle this at server level as it's not specific to IE. I mean, if that resource should not be cached, do it on the server (this as nothing to do with the browser used; it's intrisic to the resource).

For example in java with JAX-RS do it programatically for JAX-RS v1 or declativly for JAX-RS v2.

I'm sure anyone will figure out how to do it

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

How can I check if char* variable points to empty string?

Check the pointer for NULL and then using strlen to see if it returns 0.
NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior.

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Return row of Data Frame based on value in a column - R

Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]

> df[which.min(df$Amount),]
  Name Amount
2    B    120

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

DLL load failed error when importing cv2

I ran into this problem on Windows 10 (N) with a new Anaconda installation based on Python 3.7 (OpenCV version 4.0). None of the above advice helped (such as installing OpenCV from the unofficial site nor installing VC Redistributable).

I checked DLL dependencies of ...\AppData\Local\conda\conda\envs\foo\Lib\site-packages\cv2\cv2.cp37-win_amd64.pyd using dumpbin.exe according to this github issue. I noticed a library MF.dll, which I figured out belongs to Windows Media Foundation.

So I installed Media Feature Pack for N versions of Windows 10 and voilà, the issue was resolved!

How do I see the commit differences between branches in git?

I think it is matter of choice and context.I prefer to use

git log origin/master..origin/develop --oneline --no-merges

It will display commits in develop which are not in master branch.

If you want to see which files are actually modified use

git diff --stat origin/master..origin/develop --no-merges

If you don't specify arguments it will display the full diff. If you want to see visual diff, install meld on linux, or WinMerge on windows. Make sure they are the default difftools .Then use something like

git difftool -y origin/master..origin/develop --no-merges

In case you want to compare it with current branch. It is more convenient to use HEAD instead of branch name like use:

git fetch
git log origin/master..HEAD --oneline --no-merges

It will show you all the commits, about to be merged

How to write to a JSON file in the correct format

Require the JSON library, and use to_json.

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(tempHash.to_json)
end

Your temp.json file now looks like:

{"key_a":"val_a","key_b":"val_b"}

Twitter Bootstrap Multilevel Dropdown Menu

[Twitter Bootstrap v3]

To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,

CSS:

.dropdown-menu>li /* To prevent selection of text */
{   position:relative;
    -webkit-user-select: none; /* Chrome/Safari */        
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
    cursor:pointer;
}
.dropdown-menu .sub-menu 
{
    left: 100%;
    position: absolute;
    top: 0;
    display:none;
    margin-top: -1px;
    border-top-left-radius:0;
    border-bottom-left-radius:0;
    border-left-color:#fff;
    box-shadow:none;
}
.right-caret:after,.left-caret:after
 {  content:"";
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    display: inline-block;
    height: 0;
    vertical-align: middle;
    width: 0;
    margin-left:5px;
}
.right-caret:after
{   border-left: 5px solid #ffaf46;
}
.left-caret:after
{   border-right: 5px solid #ffaf46;
}

JQuery:

$(function(){
    $(".dropdown-menu > li > a.trigger").on("click",function(e){
        var current=$(this).next();
        var grandparent=$(this).parent().parent();
        if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
            $(this).toggleClass('right-caret left-caret');
        grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
        grandparent.find(".sub-menu:visible").not(current).hide();
        current.toggle();
        e.stopPropagation();
    });
    $(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
        var root=$(this).closest('.dropdown');
        root.find('.left-caret').toggleClass('right-caret left-caret');
        root.find('.sub-menu:visible').hide();
    });
});

HTML:

<div class="dropdown" style="position:relative">
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a class="trigger right-caret">Level 1</a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Level 2</a></li>
                <li>
                    <a class="trigger right-caret">Level 2</a>
                    <ul class="dropdown-menu sub-menu">
                        <li><a href="#">Level 3</a></li>
                        <li><a href="#">Level 3</a></li>
                        <li>
                            <a class="trigger right-caret">Level 3</a>
                            <ul class="dropdown-menu sub-menu">
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Level 2</a></li>
            </ul>
        </li>
        <li><a href="#">Level 1</a></li>
        <li><a href="#">Level 1</a></li>
    </ul>
</div>

iOS: present view controller programmatically

Try this code:

[self.navigationController presentViewController:controller animated:YES completion:nil];

Determine what user created objects in SQL Server

If you need a small and specific mechanism, you can search for DLL Triggers info.

How does Python return multiple values from a function?

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

I hope my answer could help you. Happy coding.

How to check if a file exists in Documents folder?

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

How can I get nth element from a list?

I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!, in your case you might search for "something that takes an Int and a list of whatevers and returns a single such whatever", namely

Int -> [a] -> a

Lo and behold, with !! as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?

Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.

Javascript: Load an Image from url and display

You have to right idea generating the url based off of the input value. The only issue is you are using window.location.href. Setting window.location.href changes the url of the current window. What you probably want to do is change the src attribute of an image.

<html>
<body>
<form>
  <input type="text" value="" id="imagename">
  <input type="button" onclick="var image = document.getElementById('the-image'); image.src='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
<img id="the-image">
</body>
</html>

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:

Get-Date (Get-Date).AddDays(-1) -format D

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

Differences between C++ string == and compare()?

compare() will return false (well, 0) if the strings are equal.

So don't take exchanging one for the other lightly.

Use whichever makes the code more readable.

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

The release is likely missing a library/plugin or the library is in the wrong directory and or from the wrong directory.

Qt intended answer: Use windeployqt. see last paragraph for explanation

Manual answer:

Create a folder named "platforms" in the same directory as your application.exe file. Copy and paste the qwindows.dll, found in the /bin of whichever compiler you used to release your application, into the "platforms" folder. Like magic it works. If the .dll is not there check plugins/platforms/ ( with plugins/ being in the same directory as bin/ ) <-- PfunnyGuy's comment.

It seems like a common issue is that the .dll was taken from the wrong compiler bin. Be sure to copy your the qwindows.dll from the same compiler as the one used to release your app.

Qt comes with platform console applications that will add all dependencies (including ones like qwindows.dll and libEGL.dll) into the folder of your deployed executable. This is the intended way to deploy your application, so you do not miss any libraries (which is the main issue with all of these answers). The application for windows is called windeployqt. There is likely a deployment console app for each OS.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Had the same problem,

All i had to do whas set the oracle shell variable:

. /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

Sorterd!

Calling an executable program using awk

It really depends :) One of the handy linux core utils (info coreutils) is xargs. If you are using awk you probably have a more involved use-case in mind - your question is not very detailled.

printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch

Will execute touch 2 4. Here touch could be replaced by your program. More info at info xargs and man xargs (really, read these). I believe you would like to replace touch with your program.

Breakdown of beforementioned script:

printf "1 2\n3 4"
# Output:
1 2
3 4

# The pipe (|) makes the output of the left command the input of
# the right command (simplified)
printf "1 2\n3 4" | awk '{ print $2 }'
# Output (of the awk command):
2
4

# xargs will execute a command with arguments. The arguments
# are made up taking the input to xargs (in this case the output
# of the awk command, which is "2 4".
printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch
# No output, but executes: `touch 2 4` which will create (or update
# timestamp if the files already exist) files with the name "2" and "4"

Update In the original answer, I used echo instead of printf. However, printf is the better and more portable alternative as was pointed out by a comment (where great links with discussions can be found).

Floating point comparison functions for C#

Although the second option is more general, the first option is better when you have an absolute tolerance, and when you have to execute many of these comparisons. If this comparison is say for every pixel in an image, the multiplication in the second options might slow your execution to unacceptable levels of performance.

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

Correct way to delete cookies server-side

For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

And use it the common way to set cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

and to delete the cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

How do I declare a 2d array in C++ using new?

Below example may help,

int main(void)
{
    double **a2d = new double*[5]; 
    /* initializing Number of rows, in this case 5 rows) */
    for (int i = 0; i < 5; i++)
    {
        a2d[i] = new double[3]; /* initializing Number of columns, in this case 3 columns */
    }

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            a2d[i][j] = 1; /* Assigning value 1 to all elements */
        }
    }

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << a2d[i][j] << endl;  /* Printing all elements to verify all elements have been correctly assigned or not */
        }
    }

    for (int i = 0; i < 5; i++)
        delete[] a2d[i];

    delete[] a2d;


    return 0;
}

How to while loop until the end of a file in Python without checking for empty line?

Don't loop through a file this way. Instead use a for loop.

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

In fact your whole program is just:

VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

That said, if you really want to keep using a while loop for some misguided reason:

while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break

How to detect the screen resolution with JavaScript?

Do you mean display resolution (eg 72 dots per inch) or pixel dimensions (browser window is currently 1000 x 800 pixels)?

Screen resolution enables you to know how thick a 10 pixel line will be in inches. Pixel dimensions tell you what percentage of the available screen height will be taken up by a 10 pixel wide horizontal line.

There's no way to know the display resolution just from Javascript since the computer itself usually doesn't know the actual dimensions of the screen, just the number of pixels. 72 dpi is the usual guess....

Note that there's a lot of confusion about display resolution, often people use the term instead of pixel resolution, but the two are quite different. See Wikipedia

Of course, you can also measure resolution in dots per cm. There is also the obscure subject of non-square dots. But I digress.

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Distinct in Linq based on only one field of the table

MoreLinq has a DistinctBy method that you can use:

It will allow you to do:

var results = table1.DistictBy(row => row.Text);

The implementation of the method (short of argument validation) is as follows:

private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
    HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
    foreach (TSource element in source)
    {
        if (knownKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

.NET obfuscation tools/strategy

I've been also using SmartAssembly. I found that Ezrinz .Net Reactor much better for me on .net applications. It obfuscates, support Mono, merges assemblies and it also also has a very nice licensing module to create trial version or link the licence to a particular machine (very easy to implement). Price is also very competitive and when I needed support they where fast. Eziriz

Just to be clear I'm just a custumer who likes the product and not in any way related with the company.

How to programmatically take a screenshot on Android?

You can try the following library: http://code.google.com/p/android-screenshot-library/ Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.

Detecting attribute change of value of an attribute I made

You can use MutationObserver to track attribute changes including data-* changes. For example:

_x000D_
_x000D_
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
  attributes: true, _x000D_
  attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
 <div id='foo'></div>_x000D_
 
_x000D_
_x000D_
_x000D_

subsetting a Python DataFrame

I'll assume that Time and Product are columns in a DataFrame, df is an instance of DataFrame, and that other variables are scalar values:

For now, you'll have to reference the DataFrame instance:

k1 = df.loc[(df.Product == p_id) & (df.Time >= start_time) & (df.Time < end_time), ['Time', 'Product']]

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators. The & operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.

In pandas 0.13 a new experimental DataFrame.query() method will be available. It's extremely similar to subset modulo the select argument:

With query() you'd do it like this:

df[['Time', 'Product']].query('Product == p_id and Month < mn and Year == yr')

Here's a simple example:

In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)})

In [10]: df
Out[10]:
  gender  price
0      m     89
1      f    123
2      f    100
3      m    104
4      m     98
5      m    103
6      f    100
7      f    109
8      f     95
9      m     87

In [11]: df.query('gender == "m" and price < 100')
Out[11]:
  gender  price
0      m     89
4      m     98
9      m     87

The final query that you're interested will even be able to take advantage of chained comparisons, like this:

k1 = df[['Time', 'Product']].query('Product == p_id and start_time <= Time < end_time')

Session 'app' error while installing APK

Looking at the error message, Android Studio tried to install older version of apk (lets say 0.5.1) while current version is lets say 0.5.2. Android Studio builds 0.5.2 but tries to install 0.5.1 for some reason.

I have turned off Instant Run, invalidated and restarted, rebuilt project and didn't help.

Solution worked for me is to uninstall the app, then change the current branch on VCS to some other branch. Then come again to latest branch and Rebuilt, Install the APK again.

Python datetime to string without microsecond component

This is the way I do it. ISO format:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

You can replace the 'T' if you don't want ISO format:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'

How to decrypt a password from SQL server?

You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:

USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash) 
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO

Twitter Bootstrap - add top space between rows

Editing or overriding the row in Twitter bootstrap is a bad idea, because this is a core part of the page scaffolding and you will need rows without a top margin.

To solve this, instead create a new class "top-buffer" that adds the standard margin that you need.

.top-buffer { margin-top:20px; }

And then use it on the row divs where you need a top margin.

<div class="row top-buffer"> ...

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

angular2: how to copy object into another object

Object.assign will only work in single level of object reference.

To do a copy in any depth use as below:

let x = {'a':'a','b':{'c':'c'}};
let y = JSON.parse(JSON.stringify(x));

If want to use any library instead then go with the loadash.js library.

Regular Expression for alphanumeric and underscores

The following regex matches alphanumeric characters and underscore:

^[a-zA-Z0-9_]+$

For example, in Perl:

#!/usr/bin/perl -w

my $arg1 = $ARGV[0];

# check that the string contains *only* one or more alphanumeric chars or underscores
if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
  print "Failed.\n";
} else {
    print "Success.\n";
}

In PowerShell, how can I test if a variable holds a numeric value?

Each numeric type has its own value. See TypeCode enum definition: https://docs.microsoft.com/en-us/dotnet/api/system.typecode?view=netframework-4.8 Based on this info, all your numeric type-values are in the range from 5 to 15. This means, you can write the condition-check like this:

$typeValue = $x.getTypeCode().value__
if ($typeValue -ge 5 -and $typeValue -le 15) {"x has a numeric type!"}

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

How to delete rows from a pandas DataFrame based on a conditional expression

If you want to drop rows of data frame on the basis of some complicated condition on the column value then writing that in the way shown above can be complicated. I have the following simpler solution which always works. Let us assume that you want to drop the column with 'header' so get that column in a list first.

text_data = df['name'].tolist()

now apply some function on the every element of the list and put that in a panda series:

text_length = pd.Series([func(t) for t in text_data])

in my case I was just trying to get the number of tokens:

text_length = pd.Series([len(t.split()) for t in text_data])

now add one extra column with the above series in the data frame:

df = df.assign(text_length = text_length .values)

now we can apply condition on the new column such as:

df = df[df.text_length  >  10]
def pass_filter(df, label, length, pass_type):

    text_data = df[label].tolist()

    text_length = pd.Series([len(t.split()) for t in text_data])

    df = df.assign(text_length = text_length .values)

    if pass_type == 'high':
        df = df[df.text_length  >  length]

    if pass_type == 'low':
        df = df[df.text_length  <  length]

    df = df.drop(columns=['text_length'])

    return df

Android Facebook integration with invalid key hash

I fixed this by adding the following into MainApplication.onCreate:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "com.genolingo.genolingo",
                           PackageManager.GET_SIGNATURES);

    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
        KeyHash.addKeyHash(hash);
    }
}
catch (PackageManager.NameNotFoundException e) {
    Log.e("PackageInfoError:", "NameNotFoundException");
}
catch (NoSuchAlgorithmException e) {
    Log.e("PackageInfoError:", "NoSuchAlgorithmException");
}

I then uploaded this to the Google developer console and then downloaded the derived APK which, for whatever reason, has a totally different key hash.

I then used LogCat to determine the new key hash and added it Facebook as other users have outlined.

Spring MVC UTF-8 Encoding

Depending on how you render your view, you may also need:

@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

Is there a float input type in HTML5?

<input type="number" step="any">

This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Rename all files in directory from $filename_h to $filename_half?

Try rename command:

rename 's/_h.png/_half.png/' *.png

Update:

example usage:

create some content

$ mkdir /tmp/foo
$ cd /tmp/foo
$ touch one_h.png two_h.png three_h.png
$ ls 
one_h.png  three_h.png  two_h.png

test solution:

$ rename 's/_h.png/_half.png/' *.png
$ ls
one_half.png  three_half.png  two_half.png

int *array = new int[n]; what is this function actually doing?

In C/C++, pointers and arrays are (almost) equivalent. int *a; a[0]; will return *a, and a[1]; will return *(a + 1)

But array can't change the pointer it points to while pointer can.

new int[n] will allocate some spaces for the "array"

Most Pythonic way to provide global configuration variables in config.py?

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:

#globals.py

class dbinfo :      # for database globals
    username = 'abcd'
    password = 'xyz'

class runtime :
    debug = False
    output = 'stdio'

Then, if you have two code files c1.py and c2.py, both can have at the top

import globals as gl

Now all code can access and set values, as such:

gl.runtime.debug = False
print(gl.dbinfo.username)

People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.

By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.

This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

Recursive file search using PowerShell

Filter using wildcards:

Get-ChildItem -Filter CopyForBuild* -Include *.bat,*.cmd -Exclude *.old.cmd,*.old.bat -Recurse

Filtering using a regular expression:

Get-ChildItem -Path "V:\Myfolder" -Recurse
| Where-Object { $_.Name -match '\ACopyForBuild\.[(bat)|(cmd)]\Z' }

How to style CSS role

please use :

 #content[role=main]{
   your style here
}

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

HTML input fields does not get focus when clicked

I had this problem too, and in my case I found that the color of the font was the same color of the background, so it looked like nothing happened.

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

If you accidentally write beyond the block allocated with alloca (due to a buffer overflow for example), then you will overwrite the return address of your function, because that one is located "above" on the stack, i.e. after your allocated block.

_alloca block on the stack

The consequence of this is two-fold:

  1. The program will crash spectacularly and it will be impossible to tell why or where it crashed (stack will most likely unwind to a random address due to the overwritten frame pointer).

  2. It makes buffer overflow many times more dangerous, since a malicious user can craft a special payload which would be put on the stack and can therefore end up executed.

In contrast, if you write beyond a block on the heap you "just" get heap corruption. The program will probably terminate unexpectedly but will unwind the stack properly, thereby reducing the chance of malicious code execution.

How can I see what I am about to push with git?

Use git gui, there you can see a list of what changed in your actual commit. You can also use gitk wich provides an easy interface for reflogs. Just compare between remotes/... and master to see, what will be pushed. It provides an interface similar to your screenshot.

Both programs are included in git.

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

if __name__ == '__main__':
    Example().main()

But you really shouldn't be using a class just to run your main code.

How to validate Google reCAPTCHA v3 on server side?

In the example above. For me, this if($response.success==false) thing does not work. Here is correct PHP code:

$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);

if (isset($data->success) AND $data->success==true) {
            // everything is ok!
} else {
            // spam
}

Do not want scientific notation on plot axis

You could try lattice:

require(lattice)
x <- 1:100000
y <- 1:100000
xyplot(y~x, scales=list(x = list(log = 10)), type="l")

enter image description here

NullPointerException in Java with no StackTrace

We have seen this same behavior in the past. It turned out that, for some crazy reason, if a NullPointerException occurred at the same place in the code multiple times, after a while using Log.error(String, Throwable) would stop including full stack traces.

Try looking further back in your log. You may find the culprit.

EDIT: this bug sounds relevant, but it was fixed so long ago it's probably not the cause.

How to concatenate strings in django templates?

extends has no facility for this. Either put the entire template path in a context variable and use that, or copy the exist template tag and modify it appropriately.

git replacing LF with CRLF

Git has three modes of how it treats line endings:

$ git config core.autocrlf
# that command will print "true" or "false" or "input"

You can set the mode to use by adding an additional parameter of true or false to the above command line.

If core.autocrlf is set to true, that means that any time you add a file to the git repo that git thinks is a text file, it will turn all CRLF line endings to just LF before it stores it in the commit. Whenever you git checkout something, all text files automatically will have their LF line endings converted to CRLF endings. This allows development of a project across platforms that use different line-ending styles without commits being very noisy because each editor changes the line ending style as the line ending style is always consistently LF.

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

If core.autocrlf is set to false, no line-ending conversion is ever performed, so text files are checked in as-is. This usually works ok, as long as all your developers are either on Linux or all on Windows. But in my experience I still tend to get text files with mixed line endings that end up causing problems.

My personal preference is to leave the setting turned ON, as a Windows developer.

See http://kernel.org/pub/software/scm/git/docs/git-config.html for updated info that includes the "input" value.

jQuery - Fancybox: But I don't want scrollbars!

My 2 cents, write

*{ margin:0; padding:0; }

in your target page main css, add a content div with the height size of all your elements, don't touch the .js, listo, saludos

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

How can I run code on a background thread on Android?

Simple 3-Liner

A simple way of doing this that I found as a comment by @awardak in Brandon Rude's answer:

new Thread( new Runnable() { @Override public void run() { 
  // Run whatever background code you want here.
} } ).start();

I'm not sure if, or how , this is better than using AsyncTask.execute but it seems to work for us. Any comments as to the difference would be appreciated.

Thanks, @awardak!

What does the DOCKER_HOST variable do?

It points to the docker host! I followed these steps:

$ boot2docker start

Waiting for VM and Docker daemon to start...
..............................
Started.

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_HOST=tcp://192.168.59.103:2375

$ export DOCKER_HOST=tcp://192.168.59.103:2375

$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete 
511136ea3c5a: Download complete 
97fd97495e49: Download complete 
2dcbbf65536c: Download complete 
6a459d727ebb: Download complete 
8f321fc43180: Download complete 
03db2b23cf03: Download complete 
Hello world

See:
http://docs.docker.com/userguide/dockerizing/

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

Skip rows during csv import pandas

I don't have reputation to comment yet, but I want to add to alko answer for further reference.

From the docs:

skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows

How would I stop a while loop after n amount of time?

Try this module: http://pypi.python.org/pypi/interruptingcow/

from interruptingcow import timeout
try:
    with timeout(60*5, exception=RuntimeError):
        while True:
            test = 0
            if test == 5:
                break
            test = test - 1
except RuntimeError:
    pass

How can I get column names from a table in Oracle?

For SQL Server:

SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = object_id('TABLE_NAME')

Python 2: AttributeError: 'list' object has no attribute 'strip'

One possible solution I have tried right now is: (Make sure do it in general way using for, while with index)

>>> l=['Facebook;Google+;MySpace', 'Apple;Android']
>>> new1 = l[0].split(';')
>>> new1
['Facebook', 'Google+', 'MySpace']
>>> new2= l[1].split(';')`enter code here`
>>> new2
['Apple', 'Android']
>>> totalnew = new1 + new2
>>> totalnew
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Problem solved!

I was having all my website set up first in XAMMP, then I had to transfer it to LAMP, in a SUSE installation of LAMP, where I got this error.

The problem is that these parameters in the database.php file should not be initialised. Just leave username and password blank. That's just it.

(My first and lame guess would be that's because of old version of mysql, as built-in installations come with older versions.

Return Index of an Element in an Array Excel VBA

'To return the position of an element within any-dimension array  
'Returns 0 if the element is not in the array, and -1 if there is an error  
Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long  
Dim pos As Long, item As Variant  

posInArray = -1  
If IsArray(aArray) Then  
    If not IsEmpty(aArray) Then  
        pos = 1  
        For Each item In aArray  
            If itemSearched = item Then  
                posInArray = pos  
                Exit Function  
            End If  
            pos = pos + 1  
        Next item  
        posInArray = 0  
    End If  
End If

End Function

Can't create handler inside thread which has not called Looper.prepare()

Try running you asyntask from the UI thread. I faced this issue when I wasn't doing the same!

show/hide a div on hover and hover out

You could use jQuery to show the div, and set it at wherever your mouse is:

html:

<!DOCTYPE html>
<html>

  <head>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>

  <body>
    <div id="trigger">
      <h1>Hover me!</h1>
      <p>Ill show you wonderful things</p>
    </div>
    <div id="secret">
     shhhh
    </div>
    <script src="script.js"></script>
  </body>

</html>

styles:

#trigger {
  border: 1px solid black;
}
#secret {
  display:none;
  top:0;  
  position:absolute;
  background: grey;
  color:white;
  width: 50%;
}

js:

$("#trigger").hover(function(e){
    $("#secret").show().css('top', e.pageY + "px").css('left', e.pageX + "px");
  },function(e){
    $("#secret").hide()
})

You can find the example here Cheers! http://plnkr.co/edit/LAhs8X9F8N3ft7qFvjzy?p=preview

T-SQL substring - separating first and last name

For the last name as in US standards (i.e., last word in the [Full Name] column) and considering first name to include a possible middle initial, middle name, etc.:

SELECT DISTINCT
             [Full Name]
            ,REVERSE([Full Name])                   --  to visualize what the formula is doing
            ,CHARINDEX(' ', REVERSE([Full Name]))   --  finds the last space in the string
            ,[Last Name]    =   REVERSE(RTRIM(LTRIM(LEFT(REVERSE([Full Name]), CHARINDEX(' ', REVERSE([Full Name]))))))
            ,[First Name]   =   RTRIM(LTRIM(LEFT([Full Name], LEN([Full Name]) - CHARINDEX(' ', REVERSE([Full Name])))))

FROM ...

Note that this assumes [Full Name] has no spaces before or after the actual string. Otherwise, use RTRIM and LTRIM to remove these.

How do operator.itemgetter() and sort() work?

a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

How do I change the text of a span element using JavaScript?

Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!

The right way:

span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);

For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP

Edited nov 4th 2017:

Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.

Leave only two decimal places after the dot

double doublVal = 123.45678;

There are two ways.

  1. for display in string:

    String.Format("{0:0.00}", doublVal );
    
  2. for geting again Double

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    

How can I run NUnit tests in Visual Studio 2017?

For anyone having issues with Visual Studio 2019:

I had to first open menu Test ? Windows ? Test Explorer, and run the tests from there, before the option to Run / Debug tests would show up on the right click menu.

How to remove all numbers from string?

Use some regex like [0-9] or \d:

$words = preg_replace('/\d+/', '', $words );

You might want to read the preg_replace() documentation as this is directly shown there.

How to create a drop shadow only on one side of an element?

If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)_x000D_
}
_x000D_
<div>_x000D_
<p>Foobar</p>_x000D_
<p>test</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

How to set default value for form field in Symfony2?

I've contemplated this a few times in the past so thought I'd jot down the different ideas I've had / used. Something might be of use, but none are "perfect" Symfony2 solutions.

Constructor In the Entity you can do $this->setBar('default value'); but this is called every time you load the entity (db or not) and is a bit messy. It does however work for every field type as you can create dates or whatever else you need.

If statements within get's I wouldn't, but you could.

return ( ! $this->hasFoo() ) ? 'default' : $this->foo;

Factory / instance. Call a static function / secondary class which provides you a default Entity pre-populated with data. E.g.

function getFactory() {
    $obj = new static();
    $obj->setBar('foo');
    $obj->setFoo('bar');

   return $obj;
}

Not really ideal given you'll have to maintain this function if you add extra fields, but it does mean you're separating the data setters / default and that which is generated from the db. Similarly you can have multiple getFactories should you want different defaulted data.

Extended / Reflection entities Create a extending Entity (e.g. FooCreate extends Foo) which gives you the defaulted data at create time (through the constructor). Similar to the Factory / instance idea just a different approach - I prefer static methods personally.

Set Data before build form In the constructors / service, you know if you have a new entity or if it was populated from the db. It's plausible therefore to call set data on the different fields when you grab a new entity. E.g.

if( ! $entity->isFromDB() ) {
     $entity->setBar('default');
     $entity->setDate( date('Y-m-d');
     ...
}
$form = $this->createForm(...)

Form Events When you create the form you set default data when creating the fields. You override this use PreSetData event listener. The problem with this is that you're duplicating the form workload / duplicating code and making it harder to maintain / understand.

Extended forms Similar to Form events, but you call the different type depending on if it's a db / new entity. By this I mean you have FooType which defines your edit form, BarType extends FooType this and sets all the data to the fields. In your controller you then simply choose which form type to instigate. This sucks if you have a custom theme though and like events, creates too much maintenance for my liking.

Twig You can create your own theme and default the data using the value option too when you do it on a per-field basis. There is nothing stopping you wrapping this into a form theme either should you wish to keep your templates clean and the form reusable. e.g.

form_widget(form.foo, {attr: { value : default } });

JS It'd be trivial to populate the form with a JS function if the fields are empty. You could do something with placeholders for example. This is a bad, bad idea though.

Forms as a service For one of the big form based projects I did, I created a service which generated all the forms, did all the processing etc. This was because the forms were to be used across multiple controllers in multiple environments and whilst the forms were generated / handled in the same way, they were displayed / interacted with differently (e.g. error handling, redirections etc). The beauty of this approach was that you can default data, do everything you need, handle errors generically etc and it's all encapsulated in one place.

Conclusion As I see it, you'll run into the same issue time and time again - where is the defaulted data to live?

  • If you store it at db/doctrine level what happens if you don't want to store the default every time?
  • If you store it at Entity level what happens if you want to re-use that entity elsewhere without any data in it?
  • If you store it at Entity Level and add a new field, do you want the previous versions to have that default value upon editing? Same goes for the default in the DB...
  • If you store it at the form level, is that obvious when you come to maintain the code later?
  • If it's in the constructor what happens if you use the form in multiple places?
  • If you push it to JS level then you've gone too far - the data shouldn't be in the view never mind JS (and we're ignoring compatibility, rendering errors etc)
  • The service is great if like me you're using it in multiple places, but it's overkill for a simple add / edit form on one site...

To that end, I've approached the problem differently each time. For example, a signup form "newsletter" option is easily (and logically) set in the constructor just before creating the form. When I was building forms collections which were linked together (e.g. which radio buttons in different form types linked together) then I've used Event Listeners. When I've built a more complicated entity (e.g. one which required children or lots of defaulted data) I've used a function (e.g. 'getFactory') to create it element as I need it.

I don't think there is one "right" approach as every time I've had this requirement it's been slightly different.

Good luck! I hope I've given you some food for thought at any rate and didn't ramble too much ;)

Keeping ASP.NET Session Open / Alive

In regards to veggerby's solution, if you are trying to implement it on a VB app, be careful trying to run the supplied code through a translator. The following will work:

Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState

Public Class SessionHeartbeatHttpHandler
    Implements IHttpHandler
    Implements IRequiresSessionState

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Session("Heartbeat") = DateTime.Now
    End Sub
End Class

Also, instead of calling like heartbeat() function like:

 setTimeout("heartbeat()", 300000);

Instead, call it like:

 setInterval(function () { heartbeat(); }, 300000);

Number one, setTimeout only fires once whereas setInterval will fire repeatedly. Number two, calling heartbeat() like a string didn't work for me, whereas calling it like an actual function did.

And I can absolutely 100% confirm that this solution will overcome GoDaddy's ridiculous decision to force a 5 minute apppool session in Plesk!

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

How to find which columns contain any NaN value in Pandas dataframe

Both of these should work:

df.isnull().sum()
df.isna().sum()

DataFrame methods isna() or isnull() are completely identical.

Note: Empty strings '' is considered as False (not considered NA)

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

What is the Sign Off feature in Git for?

Sign-off is a line at the end of the commit message which certifies who is the author of the commit. Its main purpose is to improve tracking of who did what, especially with patches.

Example commit:

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

It should contain the user real name if used for an open-source project.

If branch maintainer need to slightly modify patches in order to merge them, he could ask the submitter to rediff, but it would be counter-productive. He can adjust the code and put his sign-off at the end so the original author still gets credit for the patch.

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

[Project Maintainer: Renamed test methods according to naming convention.]
Signed-off-by: Project Maintainer <[email protected]>

Source: http://gerrit.googlecode.com/svn/documentation/2.0/user-signedoffby.html

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

Set an empty DateTime variable

Either:

DateTime dt = new DateTime();

or

DateTime dt = default(DateTime);

iPhone hide Navigation Bar only on first page

Hiding navigation bar only on first page can be achieved through storyboard as well. On storyboard, goto Navigation Controller Scene->Navigation Bar. And select 'Hidden' property from the Attributes inspector. This will hide navigation bar starting from first viewcontroller until its made visible for the required viewcontroller.

Navigation bar can be set back to visible in ViewController's ViewWillAppear callback.

-(void)viewWillAppear:(BOOL)animated {

    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];                                                  
}

Select specific row from mysql table

SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;

you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

Laravel 5 not finding css files

This works for me

If you migrated .htaccess file from public directory to project folder and altered server.php to index.php in project folder then this should works for you.

<link rel="stylesheet" href="{{ asset('public/css/app.css') }}" type="text/css">

Thanks

Handling InterruptedException in Java

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

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

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

Trigger insert old values- values that was updated

In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx

How to use CURL via a proxy?

I have explained use of various CURL options required for CURL PROXY.

$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);         // URL for CURL call
curl_setopt($ch, CURLOPT_PROXY, $proxy);     // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);   // Use if proxy have username and password
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // If expected to call with specific PROXY type
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  // If url has redirects then go to the final redirected URL.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);  // Do not outputting it out directly on screen.
curl_setopt($ch, CURLOPT_HEADER, 1);   // If you want Header information of response else make 0
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

How to get JSON from URL in JavaScript?

//Resolved
const fetchPromise1 = fetch(url);
    fetchPromise1.then(response => {
      console.log(response);
    });


//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

How to replace space with comma using sed?

I just confirmed that:

cat file.txt | sed "s/\s/,/g"

successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

Use the Format function.

Format(Date, "yyyy-mm-dd hh:MM:ss")

Hiding elements in responsive layout?

You can enter these module class suffixes for any module to better control where it will show or be hidden.

.visible-phone  
.visible-tablet     
.visible-desktop    
.hidden-phone   
.hidden-tablet  
.hidden-desktop 

http://twitter.github.com/bootstrap/scaffolding.html scroll to bottom

How to list the files in current directory?

Had a quick snoop around for this one, but this looks like it should work. I haven't tested it yet though.

    File f = new File("."); // current directory

    File[] files = f.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            System.out.print("directory:");
        } else {
            System.out.print("     file:");
        }
        System.out.println(file.getCanonicalPath());
    }

How to move files from one git repo to another (not a clone), preserving history

Having had a similar itch to scratch (altough only for some files of a given repository) this script proved to be really helpful: git-import

The short version is that it creates patch files of the given file or directory ($object) from the existing repository:

cd old_repo
git format-patch --thread -o "$temp" --root -- "$object"

which then get applied to a new repository:

cd new_repo
git am "$temp"/*.patch 

For details please look up:

How to get current value of RxJS Subject or Observable?

The only way you should be getting values "out of" an Observable/Subject is with subscribe!

If you're using getValue() you're doing something imperative in declarative paradigm. It's there as an escape hatch, but 99.9% of the time you should NOT use getValue(). There are a few interesting things that getValue() will do: It will throw an error if the subject has been unsubscribed, it will prevent you from getting a value if the subject is dead because it's errored, etc. But, again, it's there as an escape hatch for rare circumstances.

There are several ways of getting the latest value from a Subject or Observable in a "Rx-y" way:

  1. Using BehaviorSubject: But actually subscribing to it. When you first subscribe to BehaviorSubject it will synchronously send the previous value it received or was initialized with.
  2. Using a ReplaySubject(N): This will cache N values and replay them to new subscribers.
  3. A.withLatestFrom(B): Use this operator to get the most recent value from observable B when observable A emits. Will give you both values in an array [a, b].
  4. A.combineLatest(B): Use this operator to get the most recent values from A and B every time either A or B emits. Will give you both values in an array.
  5. shareReplay(): Makes an Observable multicast through a ReplaySubject, but allows you to retry the observable on error. (Basically it gives you that promise-y caching behavior).
  6. publishReplay(), publishBehavior(initialValue), multicast(subject: BehaviorSubject | ReplaySubject), etc: Other operators that leverage BehaviorSubject and ReplaySubject. Different flavors of the same thing, they basically multicast the source observable by funneling all notifications through a subject. You need to call connect() to subscribe to the source with the subject.

Get epoch for a specific date using Javascript

Number(new Date(2010, 6, 26))

Works the same way as things above. If you need seconds don't forget to / 1000

Get and Set Screen Resolution

Answer from different solutions to get Display Resolution

  1. Get the scaling factor

  2. Get Screen.PrimaryScreen.Bounds.Width and Screen.PrimaryScreen.Bounds.Height multiple by scaling factor result

    #region Display Resolution
    
     [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
     public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
    
     public enum DeviceCap
     {
         VERTRES = 10,
         DESKTOPVERTRES = 117
     }
    
    
     public static double GetWindowsScreenScalingFactor(bool percentage = true)
     {
         //Create Graphics object from the current windows handle
         Graphics GraphicsObject = Graphics.FromHwnd(IntPtr.Zero);
         //Get Handle to the device context associated with this Graphics object
         IntPtr DeviceContextHandle = GraphicsObject.GetHdc();
         //Call GetDeviceCaps with the Handle to retrieve the Screen Height
         int LogicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.VERTRES);
         int PhysicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.DESKTOPVERTRES);
         //Divide the Screen Heights to get the scaling factor and round it to two decimals
         double ScreenScalingFactor = Math.Round(PhysicalScreenHeight / (double)LogicalScreenHeight, 2);
         //If requested as percentage - convert it
         if (percentage)
         {
             ScreenScalingFactor *= 100.0;
         }
         //Release the Handle and Dispose of the GraphicsObject object
         GraphicsObject.ReleaseHdc(DeviceContextHandle);
         GraphicsObject.Dispose();
         //Return the Scaling Factor
         return ScreenScalingFactor;
     }
    
     public static Size GetDisplayResolution()
     {
         var sf = GetWindowsScreenScalingFactor(false);
         var screenWidth = Screen.PrimaryScreen.Bounds.Width * sf;
         var screenHeight = Screen.PrimaryScreen.Bounds.Height * sf;
         return new Size((int)screenWidth, (int)screenHeight);
     }
    
     #endregion
    

to check display resolution

var size = GetDisplayResolution();
Console.WriteLine("Display Resoluton: " + size.Width + "x" + size.Height);

How to Flatten a Multidimensional Array?

The trick is passing the both the source and destination arrays by reference.

function flatten_array(&$arr, &$dst) {
    if(!isset($dst) || !is_array($dst)) {
        $dst = array();
    }
    if(!is_array($arr)) {
        $dst[] = $arr;
    } else {
        foreach($arr as &$subject) {
            flatten_array($subject, $dst);
        }
    }
}

$recursive = array('1', array('2','3',array('4',array('5','6')),'7',array(array(array('8'),'9'),'10')));
echo "Recursive: \r\n";
print_r($recursive);
$flat = null;
flatten_array($recursive, $flat);

echo "Flat: \r\n";
print_r($flat);

// If you change line 3 to $dst[] = &$arr; , you won't waste memory,
// since all you're doing is copying references, and imploding the array 
// into a string will be both memory efficient and fast:)

echo "String:\r\n";
echo implode(',',$flat);

How to get the number of threads in a Java process

java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

the below piece of code should do what yoiu are looking for:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    System.out.println(s);
    scan.close();
}

How do I set cell value to Date and apply default Excel date format?

This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Redirect echo output in shell script to logfile

#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"

Output:

> ./above_script.sh                                                                
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file

Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html

Opening the Settings app from another app

As mentioned by Karan Dua this is now possible in iOS8 using UIApplicationOpenSettingsURLString see Apple's Documentation.

Example:

Swift 4.2

UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)

In Swift 3:

UIApplication.shared.open(URL(string:UIApplicationOpenSettingsURLString)!)

In Swift 2:

UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)

In Objective-C

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Prior to iOS 8:

You can not. As you said this has been covered many times and that pop up asking you to turn on location services is supplied by Apple and not by the App itself. That is why it is able to the open the settings application.

Here are a few related questions & articles:

is it possible to open Settings App using openURL?

Programmatically opening the settings app (iPhone)

How can I open the Settings app when the user presses a button?

iPhone: Opening Application Preferences Panel From App

Open UIPickerView by clicking on an entry in the app's preferences - How to?

Open the Settings app?

iOS: You’re Doing Settings Wrong

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.

  1. Generate CA and the certificates (you can use openssl: Generating CA and self-signed certificates.
  2. Install root certificate (*.cer file) on the device - you can open it by Safari and it should redirect you to Settings
  3. When the certificated is installed, go to Certificate Trust Settings (Settings > General > About > Certificate Trust Settings) as in MattP answer.

If it is not possible then you need to change server trust evaluation.

More info in this document: Technical Q&A QA1948 HTTPS and Test Servers

commons httpclient - Adding query string parameters to GET/POST request

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

What is the result of % in Python?

Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.

http://docs.python.org/reference/expressions.html

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

in a "using" block is a SqlConnection closed on return or exception?

Using generates a try / finally around the object being allocated and calls Dispose() for you.

It saves you the hassle of manually creating the try / finally block and calling Dispose()

Excel function to get first word from sentence in other cell

How about something like

=LEFT(A1,SEARCH(" ",A1)-1)

or

=LEFT(A1,SEARCH("<b>",A1)-1)

Have a look at MS Excel: Search Function and Excel 2007 LEFT Function

How can I enable Assembly binding logging?

When I had the same problem I fixed it by deleting the existing key.snk in that project and adding a new key.

Read response body in JAX-RS client from a post request

Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

Regards

Carlos Cepeda

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

Transfer data from one database to another database

This can be achieved by a T-SQL statement, if you are aware that FROM clause can specify database for table name.

insert into database1..MyTable
select from database2..MyTable

Here is how Microsoft explains the syntax: https://docs.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver15

If the table or view exists in another database on the same instance of SQL Server, use a fully qualified name in the form database.schema.object_name.

schema_name can be omitted, like above, which means the default schema of the current user. By default, it's dbo.

Add any filtering to columns/rows if you want to. Be sure to create any new table before moving data.

How do you read CSS rule values with JavaScript?

function getStyle(className) {
    document.styleSheets.item("menu").cssRules.item(className).cssText;
}
getStyle('.test')

Note : "menu" is an element ID which you have applied CSS. "className" a css class name which we need to get its text.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

My case was different the child view already had a parent view i am adding the child view inside parent view to different parent. example code below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/lineGap"
>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black1"
    android:layout_gravity="center"
    android:gravity="center"
    />

</LinearLayout>

And i was inflating this view and adding to another LinearLayout, then i removed the LinaarLayout from the above layout and its started working

below code fixed the issue:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:textColor="@color/black1" />

How to resize images proportionally / keeping the aspect ratio?

This issue can be solved by CSS.

.image{
 max-width:*px;
}

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

Get value of Span Text

<script type="text/javascript">
document.getElementById('button1').onChange = function () {
    document.getElementById('hidden_field_id').value = document.getElementById('span_id').innerHTML;
}
</script>

Creating SolidColorBrush from hex color value

If you don't want to deal with the pain of the conversion every time simply create an extension method.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Then use like this: BackColor = "#FFADD8E6".ToBrush()

Alternately if you could provide a method to do the same thing.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

How to generate random number with the specific length in python

I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

Return multiple values from a function in swift

Swift 3

func getTime() -> (hour: Int, minute: Int,second: Int) {
        let hour = 1
        let minute = 20
        let second = 55
        return (hour, minute, second)
    }

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)

How to register ASP.NET 2.0 to web server(IIS7)?

The system I was working on is Windows Server 2008 Standard with IIS 7 (I guess that my experience will apply for all Windows systems of the same age).

Running

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

SEEMED to work, as

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -lv

showed the .Net framework v4 registered with IIS.

But, running the same for .Net v2, namely

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir

did NOT result in

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -lv

showing the framework registered.

(And, for me, the installer for Kofax Capture Network Server was still missing ASP.NET.)

The solution was:

  • Open Server Manager
  • Go to Roles/Web Server (IIS)
  • Push Add Role Services
  • check ASP.NET under Application Development (and press Install)

After that, aspnet_regiis.exe -lv (either version) shows the framework registered. (And the Kofax installer was also happy and worked.)

What is Node.js' Connect, Express and "middleware"?

Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.

Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.

How to convert latitude or longitude to meters?

    'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
                         ByVal lat2 As Double, ByVal lon2 As Double, _
                         Optional ByVal unit As Char = "M"c) As Double
    Dim theta As Double = lon1 - lon2
    Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
                            Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
                            Math.Cos(deg2rad(theta))
    dist = Math.Acos(dist)
    dist = rad2deg(dist)
    dist = dist * 60 * 1.1515
    If unit = "K" Then
        dist = dist * 1.609344
    ElseIf unit = "N" Then
        dist = dist * 0.8684
    End If
    Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
                         ByVal lat2 As Double, ByVal lon2 As Double, _
                         Optional ByVal unit As Char = "M"c) As Double
    Dim R As Double = 6371 'earth radius in km
    Dim dLat As Double
    Dim dLon As Double
    Dim a As Double
    Dim c As Double
    Dim d As Double
    dLat = deg2rad(lat2 - lat1)
    dLon = deg2rad((lon2 - lon1))
    a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
            Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
    c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
    d = R * c
    Select Case unit.ToString.ToUpper
        Case "M"c
            d = d * 0.62137119
        Case "N"c
            d = d * 0.5399568
    End Select
    Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
    Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
    Return rad / Math.PI * 180.0
End Function

How to diff a commit with its parent?

Uses aliases, so doesn't answer your question exactly but I find these useful for doing what you intend...

alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"

alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"

Export database schema into SQL file

i wrote this sp to create automatically the schema with all things, pk, fk, partitions, constraints... I wrote it to run in same sp.

IMPORTANT!! before exec

    create type TableType as table (ObjectID int)

here the SP:

create PROCEDURE [dbo].[util_ScriptTable] 
     @DBName SYSNAME
    ,@schema sysname
    ,@TableName SYSNAME
    ,@IncludeConstraints BIT = 1
    ,@IncludeIndexes BIT = 1
    ,@NewTableSchema sysname
    ,@NewTableName SYSNAME = NULL
    ,@UseSystemDataTypes BIT = 0
    ,@script varchar(max) output
AS 
BEGIN try
    if not exists (select * from sys.types where name = 'TableType')
        create type TableType as table (ObjectID int)--drop type TableType
    
    declare @sql nvarchar(max)
  
    DECLARE @MainDefinition TABLE (FieldValue VARCHAR(200))
    --DECLARE @DBName SYSNAME
    DECLARE @ClusteredPK BIT
    DECLARE @TableSchema NVARCHAR(255)
    
    --SET @DBName = DB_NAME(DB_ID())
    SELECT @TableName = name FROM sysobjects WHERE id = OBJECT_ID(@TableName)
    
    DECLARE @ShowFields TABLE (FieldID INT IDENTITY(1,1)
                                        ,DatabaseName VARCHAR(100)
                                        ,TableOwner VARCHAR(100)
                                        ,TableName VARCHAR(100)
                                        ,FieldName VARCHAR(100)
                                        ,ColumnPosition INT
                                        ,ColumnDefaultValue VARCHAR(100)
                                        ,ColumnDefaultName VARCHAR(100)
                                        ,IsNullable BIT
                                        ,DataType VARCHAR(100)
                                        ,MaxLength varchar(10)
                                        ,NumericPrecision INT
                                        ,NumericScale INT
                                        ,DomainName VARCHAR(100)
                                        ,FieldListingName VARCHAR(110)
                                        ,FieldDefinition CHAR(1)
                                        ,IdentityColumn BIT
                                        ,IdentitySeed INT
                                        ,IdentityIncrement INT
                                        ,IsCharColumn BIT 
                                        ,IsComputed varchar(255))
    
    DECLARE @HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
                                        ,Flds VARCHAR(4000)
                                        ,FldValue CHAR(1) DEFAULT(0))
    
    DECLARE @PKObjectID TABLE(ObjectID INT)
    
    DECLARE @Uniques TABLE(ObjectID INT)
    
    DECLARE @HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
                                                ,Flds VARCHAR(4000)
                                                ,FldValue CHAR(1) DEFAULT(0))
    
    DECLARE @Definition TABLE(DefinitionID SMALLINT IDENTITY(1,1)
                                        ,FieldValue VARCHAR(200))

  
  set @sql=
  '
  use '+@DBName+'
  SELECT distinct DB_NAME()
            ,inf.TABLE_SCHEMA
            ,inf.TABLE_NAME
            ,''[''+inf.COLUMN_NAME+'']'' as COLUMN_NAME
            ,CAST(inf.ORDINAL_POSITION AS INT)
            ,inf.COLUMN_DEFAULT
            ,dobj.name AS ColumnDefaultName
            ,CASE WHEN inf.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
            ,inf.DATA_TYPE
            ,case inf.CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(inf.CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
            ,CAST(inf.NUMERIC_PRECISION AS INT)
            ,CAST(inf.NUMERIC_SCALE AS INT)
            ,inf.DOMAIN_NAME
            ,inf.COLUMN_NAME + '',''
            ,'''' AS FieldDefinition
            --caso di viste, dà come campo identity ma nn dà i valori, quindi lo ignoro
            ,CASE WHEN ic.object_id IS not NULL and ic.seed_value is not null THEN 1 ELSE 0 END AS IdentityColumn--CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
            ,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
            ,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
            ,CASE WHEN c.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn 
            ,cc.definition 
            from (select schema_id,object_id,name from sys.views union all select schema_id,object_id,name from sys.tables)t
                --sys.tables t
            join sys.schemas s on t.schema_id=s.schema_id
            JOIN sys.columns c ON  t.object_id=c.object_id --AND s.schema_id=c.schema_id
            LEFT JOIN sys.identity_columns ic ON t.object_id=ic.object_id AND c.column_id=ic.column_id
            left JOIN sys.types st ON st.system_type_id=c.system_type_id and st.principal_id=t.object_id--COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
            LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = c.default_object_id AND dobj.type = ''D''
            left join sys.computed_columns cc on t.object_id=cc.object_id and c.column_id=cc.column_id
            join INFORMATION_SCHEMA.COLUMNS inf on t.name=inf.TABLE_NAME
                                               and s.name=inf.TABLE_SCHEMA
                                               and c.name=inf.COLUMN_NAME
    WHERE inf.TABLE_NAME = @TableName and inf.TABLE_SCHEMA=@schema 
    ORDER BY inf.ORDINAL_POSITION
    '
    
  print @sql
  INSERT INTO @ShowFields( DatabaseName
                                    ,TableOwner
                                    ,TableName
                                    ,FieldName
                                    ,ColumnPosition
                                    ,ColumnDefaultValue
                                    ,ColumnDefaultName
                                    ,IsNullable
                                    ,DataType
                                    ,MaxLength
                                    ,NumericPrecision
                                    ,NumericScale
                                    ,DomainName
                                    ,FieldListingName
                                    ,FieldDefinition
                                    ,IdentityColumn
                                    ,IdentitySeed
                                    ,IdentityIncrement
                                    ,IsCharColumn
                                    ,IsComputed)
                                    
    exec sp_executesql @sql,
                       N'@TableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@schema=@schema            
    /*
    SELECT @DBName--DB_NAME()
            ,TABLE_SCHEMA
            ,TABLE_NAME
            ,COLUMN_NAME
            ,CAST(ORDINAL_POSITION AS INT)
            ,COLUMN_DEFAULT
            ,dobj.name AS ColumnDefaultName
            ,CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END
            ,DATA_TYPE
            ,CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
            ,CAST(NUMERIC_PRECISION AS INT)
            ,CAST(NUMERIC_SCALE AS INT)
            ,DOMAIN_NAME
            ,COLUMN_NAME + ','
            ,'' AS FieldDefinition
            ,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
            ,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
            ,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
            ,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn 
            FROM INFORMATION_SCHEMA.COLUMNS c
            JOIN sys.columns sc ON  c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
            LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
            JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
            LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = 'D'

    WHERE c.TABLE_NAME = @TableName
    ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
    */
    SELECT TOP 1 @TableSchema = TableOwner FROM @ShowFields
    
    INSERT INTO @HoldingArea (Flds) VALUES('(')
    
    INSERT INTO @Definition(FieldValue)VALUES('CREATE TABLE ' + CASE WHEN @NewTableName IS NOT NULL THEN @DBName + '.' + @NewTableSchema + '.' + @NewTableName ELSE @DBName + '.' + @TableSchema + '.' + @TableName END)
    INSERT INTO @Definition(FieldValue)VALUES('(')
    INSERT INTO @Definition(FieldValue)
    SELECT   CHAR(10) + FieldName + ' ' + 
        --CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN '' ELSE ',' END 
        
        CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName + 
            CASe WHEN IsNullable = 1 THEN ' NULL ' 
            ELSE ' NOT NULL ' 
            END 
        ELSE 
            case when IsComputed is null then
                UPPER(DataType) +
                CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' 
                ELSE 
                    CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')' 
                    ELSE
                        CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')' 
                        ELSE '' 
                        end  
                    end 
                END +
                CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' 
                ELSE '' 
                END +
                CASE WHEN IsNullable = 1 THEN ' NULL ' 
                ELSE ' NOT NULL ' 
                END +
                CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,@TableName,@NewTableName) + '] DEFAULT' + UPPER(ColumnDefaultValue) 
                ELSE '' 
                END 
            else
                ' as '+IsComputed+' '
            end
        END + 
        CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN '' 
        ELSE ',' 
        END 
        
    FROM    @ShowFields
    
    IF @IncludeConstraints = 1
        BEGIN    
        
        set @sql=
        '
        use '+@DBName+'
        SELECT  distinct  '',CONSTRAINT ['' + @NewTableName+''_''+replace(name,@TableName,'''') + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')'' 
           FROM ( SELECT   ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
                ,   REVERSE(SUBSTRING(REVERSE((   SELECT cp.name + '',''   
                FROM   sys.foreign_key_columns fkc   
                JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id   
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ParentColumns,   
                REVERSE(SUBSTRING(REVERSE((   SELECT cr.name + '',''   
                FROM   sys.foreign_key_columns fkc  
                JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ReferencedColumns   
                FROM sys.foreign_keys fk    
                    inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=@schema) a    
            WHERE ParentObject = @TableName    
        '
        
        print @sql
        
        INSERT INTO @Definition(FieldValue)
        exec sp_executesql @sql,
                   N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
            /*
           SELECT    ',CONSTRAINT [' + name + '] FOREIGN KEY (' + ParentColumns + ') REFERENCES [' + ReferencedObject + '](' + ReferencedColumns + ')'  
           FROM ( SELECT   ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
                ,   REVERSE(SUBSTRING(REVERSE((   SELECT cp.name + ','   
                FROM   sys.foreign_key_columns fkc   
                JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id   
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('')   )), 2, 8000)) ParentColumns,   
                REVERSE(SUBSTRING(REVERSE((   SELECT cr.name + ','   
                FROM   sys.foreign_key_columns fkc  
                JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('')   )), 2, 8000)) ReferencedColumns   
                FROM sys.foreign_keys fk    ) a    
            WHERE ParentObject = @TableName    
            */
            
            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '',CONSTRAINT ['' + @NewTableName+''_''+replace(c.name,@TableName,'''') + ''] CHECK '' + definition 
            FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=@schema    
            WHERE OBJECT_NAME(parent_object_id) = @TableName
            '
            
            print @sql
            INSERT INTO @Definition(FieldValue) 
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
            /*
            SELECT ',CONSTRAINT [' + name + '] CHECK ' + definition FROM sys.check_constraints    
            WHERE OBJECT_NAME(parent_object_id) = @TableName
            */
            
            set @sql=
            '
            use '+@DBName+'
            SELECT DISTINCT  PKObject = cco.object_id 
            FROM    sys.key_constraints cco    
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id    
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName    AND  i.type = 1 AND    is_primary_key = 1
            '
            print @sql
            INSERT INTO @PKObjectID(ObjectID) 
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@schema varchar(50)',
                               @TableName=@TableName,@schema=@schema
            /*
            SELECT DISTINCT  PKObject = cco.object_id 
            FROM    sys.key_constraints cco    
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id    
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            WHERE    OBJECT_NAME(parent_object_id) = @TableName    AND  i.type = 1 AND    is_primary_key = 1
            */
            
            set @sql=
            '
            use '+@DBName+'
            SELECT DISTINCT    PKObject = cco.object_id
            FROM    sys.key_constraints cco   
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id  
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName AND  i.type = 2 AND    is_primary_key = 0 AND    is_unique_constraint = 1
            '
            print @sql
            INSERT INTO @Uniques(ObjectID)
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@schema varchar(50)',
                               @TableName=@TableName,@schema=@schema
            /*
            SELECT DISTINCT    PKObject = cco.object_id
            FROM    sys.key_constraints cco   
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id  
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            WHERE    OBJECT_NAME(parent_object_id) = @TableName AND  i.type = 2 AND    is_primary_key = 0 AND    is_unique_constraint = 1
            */
            
            SET @ClusteredPK = CASE WHEN @@ROWCOUNT > 0 THEN 1 ELSE 0 END
            
            declare @t TableType
            insert @t select * from @PKObjectID
            declare @u TableType
            insert @u select * from @Uniques
            
            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '',CONSTRAINT '' + @NewTableName+''_''+replace(cco.name,@TableName,'''') + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END  WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END 
            + ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT   c.name +  + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''    
            FROM   sys.key_constraints ccok   
            LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
            LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id 
            LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id  
            WHERE i.object_id = ccok.parent_object_id AND   ccok.object_id = cco.object_id    
            order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
            FROM sys.key_constraints cco 
            inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            LEFT JOIN @U u ON cco.object_id = u.objectID
            LEFT JOIN @t pk ON cco.object_id = pk.ObjectID    
            WHERE    OBJECT_NAME(cco.parent_object_id) = @TableName 
            
            '
            
            print @sql
            INSERT INTO @Definition(FieldValue)
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50),@t TableType readonly,@u TableType readonly',
                               @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@t=@t,@u=@u
            
            /*
            SELECT ',CONSTRAINT ' + name + CASE type WHEN 'PK' THEN ' PRIMARY KEY ' + CASE WHEN pk.ObjectID IS NULL THEN ' NONCLUSTERED ' ELSE ' CLUSTERED ' END  WHEN 'UQ' THEN ' UNIQUE ' END + CASE WHEN u.ObjectID IS NOT NULL THEN ' NONCLUSTERED ' ELSE '' END 
            + '(' +REVERSE(SUBSTRING(REVERSE(( SELECT   c.name +  + CASE WHEN cc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','    
            FROM   sys.key_constraints ccok   
            LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
           LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id 
           LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id  
           WHERE i.object_id = ccok.parent_object_id AND   ccok.object_id = cco.object_id    FOR XML PATH(''))), 2, 8000)) + ')'
           FROM sys.key_constraints cco 
           LEFT JOIN @PKObjectID pk ON cco.object_id = pk.ObjectID    
           LEFT JOIN @Uniques u ON cco.object_id = u.objectID
           WHERE    OBJECT_NAME(cco.parent_object_id) = @TableName 
           */
        END
           
        INSERT INTO @Definition(FieldValue) VALUES(')')
        
        set @sql=
        '
        use '+@DBName+'
        select '' on '' + d.name + ''([''+c.name+''])''
        from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
                          join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
                          join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
                          join sys.schemas s on t.schema_id=s.schema_id
                          join sys.data_spaces d on i.data_space_id=d.data_space_id
        where t.name=@TableName and s.name=@schema
        order by key_ordinal
        '
        
        print 'x'
        print @sql
        INSERT INTO @Definition(FieldValue) 
        exec sp_executesql @sql,
                           N'@TableName varchar(50),@schema varchar(50)',
                           @TableName=@TableName,@schema=@schema
             
        IF @IncludeIndexes = 1
        BEGIN
            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '' CREATE '' + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,@TableName,@NewTableName) + ''] ON '+@DBName+'.'+@NewTableSchema+'.'+@NewTableName+' ('' 
            +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=0
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000)) + '')''+
            ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE((   SELECT name + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=1
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000))+'')'' ,'''')+''''    
            FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
                               join sys.schemas s on t.schema_id=s.schema_id   
            AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 
                where t.name=@TableName and s.name=@schema
            '
            
            print @sql
            INSERT INTO @Definition(FieldValue)    
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50), @ClusteredPK bit',
                               @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@ClusteredPK=@ClusteredPK
            
        END 
       
            /*
                
                SELECT   'CREATE ' + type_desc + ' INDEX [' + [name] COLLATE SQL_Latin1_General_CP1_CI_AS + '] ON [' +  OBJECT_NAME(object_id) + '] (' +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','   
                FROM  sys.index_columns sc  
                JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
                WHERE  OBJECT_NAME(sc.object_id) = @TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                ORDER BY index_column_id ASC   FOR XML PATH('')    )), 2, 8000)) + ')'    
                FROM sys.indexes i    
                WHERE   OBJECT_NAME(object_id) = @TableName
                AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 
               
            */
            
            INSERT INTO @MainDefinition(FieldValue)   
            SELECT FieldValue FROM @Definition    
            ORDER BY DefinitionID ASC 
            
            ----------------------------------
            --SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH('')
            set @script='use '+@DBName+' '+(SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH(''))
            
            --declare @q    varchar(max)
            --set @q=(select replace((SELECT FieldValue FROM @MainDefinition FOR XML PATH('')),'</FieldValue>',''))
            --set @script=(select REPLACE(@q,'<FieldValue>',''))
            --drop type TableType
END try
-- ##############################################################################################################################################################################
BEGIN CATCH        
    BEGIN
        -- INIZIO  Procedura in errore =========================================================================================================================================================
            PRINT '***********************************************************************************************************************************************************' 
            PRINT 'ErrorNumber               : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
            PRINT 'ErrorSeverity             : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX)) 
            PRINT 'ErrorState                : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX)) 
            PRINT 'ErrorLine                 : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX)) 
            PRINT 'ErrorMessage              : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
            PRINT '***********************************************************************************************************************************************************' 
        -- FINE  Procedura in errore =========================================================================================================================================================
    END 
        set @script=''
    return -1
END CATCH   
-- ##############################################################################################################################################################################   

to exec it:

declare @s varchar(max)
exec [util_ScriptTable]   'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,@s output
select @s

How can I reset or revert a file to a specific revision?

git-aliases, awk and shell-functions to the rescue!

git prevision <N> <filename>

where <N> is the number of revisions of the file to rollback for file <filename>.
For example, to checkout the immediate previous revision of a single file x/y/z.c, run

git prevision -1 x/y/z.c

How git prevision works?

Add the following to your gitconfig

[alias]
        prevision = "!f() { git checkout `git log --oneline $2 |  awk -v commit="$1" 'FNR == -commit+1 {print $1}'` $2;} ;f"

The command basically

  • performs a git log on the specified file and
  • picks the appropriate commit-id in the history of the file and
  • executes a git checkout to the commit-id for the specified file.

Essentially, all that one would manually do in this situation,
wrapped-up in one beautiful, efficient git-alias - git-prevision

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

How do I draw a circle in iOS Swift?

Updating @Dario's code approach for Xcode 8.2.2, Swift 3.x. Noting that in storyboard, set the Background color to "clear" to avoid a black background in the square UIView:

import UIKit
@IBDesignable
class Dot:UIView
{
    @IBInspectable var mainColor: UIColor = UIColor.clear
        {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = UIColor.clear
        {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4
        {
        didSet { print("ringThickness was set here") }
    }


    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect)
    {

        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) { drawRingFittingInsideView(rect: rect) }
    }

    internal func drawRingFittingInsideView(rect: CGRect)->()
    {
        let hw:CGFloat = ringThickness/2
        let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw,dy: hw) )

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

And if you want to control the start and end angles:

import UIKit
@IBDesignable
class Dot:UIView
{
    @IBInspectable var mainColor: UIColor = UIColor.clear
        {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = UIColor.clear
        {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4
        {
        didSet { print("ringThickness was set here") }
    }


    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect)
    {

        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) { drawRingFittingInsideView(rect: rect) }
    }

    internal func drawRingFittingInsideView(rect: CGRect)->()
    {
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = ringThickness   // your desired value

        let circlePath = UIBezierPath(
            arcCenter: CGPoint(x: halfSize, y: halfSize),
            radius: CGFloat( halfSize - (desiredLineWidth/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(Double.pi),
            clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

What is difference between monolithic and micro kernel?

In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.

The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);

In that its code is a single C file giving rise to a single process that implements all of the above services.
To exemplify the encapsulation of the Linux kernel we remark that the Linux kernel does not even have access to any of the standard C libraries. Indeed the Linux kernel cannot use rudimentary C library functions such as printf. Instead it implements its own printing function (called prints).

This seclusion of the Linux kernel and self-containment provide Linux kernel with its main advantage: the kernel resides in a single address space1 enabling all features to communicate in the fastest way possible without resorting to any type of message passing. In particular, a monolithic kernel implements all of the device drivers of the system.

This however is the main drawback of a monolithic kernel: introduction of any new unsupported hardware requires a rewrite of the kernel (in the relevant parts), recompilation of it, and re-installing the entire OS.
More importantly, if any device driver crashes the entire kernel suffers as a result. This un-modular approach to hardware additions and hardware crashes is the main argument for supporting the other extreme design approach for kernels. A microkernel is in a sense a minimalistic kernel that houses only the very basic of OS services (like process management and file system management). In a microkernel the device drivers lie outside of the kernel allowing for addition and removal of device drivers while the OS is running and require no alternations of the kernel.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

How to enable file upload on React's Material UI simple input?

You can use Material UI's Input and InputLabel components. Here's an example if you were using them to input spreadsheet files.

import { Input, InputLabel } from "@material-ui/core";

const styles = {
  hidden: {
    display: "none",
  },
  importLabel: {
    color: "black",
  },
};

<InputLabel htmlFor="import-button" style={styles.importLabel}>
    <Input
        id="import-button"
        inputProps={{
          accept:
            ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
        }}
        onChange={onInputChange}
        style={styles.hidden}
        type="file"
    />
    Import Spreadsheet
</InputLabel>

Using DISTINCT and COUNT together in a MySQL Query

FYI, this is probably faster,

SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp

than this,

SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'

How to upload a file to directory in S3 bucket using boto

I used this and it is very simple to implement

import tinys3

conn = tinys3.Connection('S3_ACCESS_KEY','S3_SECRET_KEY',tls=True)

f = open('some_file.zip','rb')
conn.upload('some_file.zip',f,'my_bucket')

https://www.smore.com/labs/tinys3/

How can I monitor the thread count of a process on linux?

ps -eLf on the shell shall give you a list of all the threads and processes currently running on the system. Or, you can run top command then hit 'H' to toggle thread listings.

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

Select2 doesn't work when embedded in a bootstrap modal

Okay, I know I'm late to the party. But let me share with you what worked for me. The tabindex and z-index solutions did not work for me.

Setting the parent of the select element worked as per the common problems listed on select2 site.

How to get the body's content of an iframe in Javascript?

AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.

Here's how to get its body content using plane old javascript. This works with both IE and Firefox.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    alert(iFrameBody.innerHTML);
 }

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

Bootstrap row class contains margin-left and margin-right which creates problems

Old topic, but I think I found another descent solution. Adding class="row" to a div will result in this CSS configuration:

.row {
    display: -webkit-box;
    display: flex;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
}

We want to keep the first 3 rules and we can do this with class="d-flex flex-wrap" (see https://getbootstrap.com/docs/4.1/utilities/flex/):

.flex-wrap {
    flex-wrap: wrap !important;
}
.d-flex {
    display: -webkit-box !important;
    display: flex !important;
}

It adds !important rules though but it shouldn't be a problem in most cases...

Get table column names in MySQL?

The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)

How should strace be used?

Strace stands out as a tool for investigating production systems where you can't afford to run these programs under a debugger. In particular, we have used strace in the following two situations:

  • Program foo seems to be in deadlock and has become unresponsive. This could be a target for gdb; however, we haven't always had the source code or sometimes were dealing with scripted languages that weren't straight-forward to run under a debugger. In this case, you run strace on an already running program and you will get the list of system calls being made. This is particularly useful if you are investigating a client/server application or an application that interacts with a database
  • Investigating why a program is slow. In particular, we had just moved to a new distributed file system and the new throughput of the system was very slow. You can specify strace with the '-T' option which will tell you how much time was spent in each system call. This helped to determine why the file system was causing things to slow down.

For an example of analyzing using strace see my answer to this question.

Could not find folder 'tools' inside SDK

I faced similar issue when the SDK tools installation was failed during the initial setup. To resolution is to download SDK tools from Android Developer Site

  • Expand "USE AN EXISTING IDE" section and download standalone SDK tools
  • Choose your destination as (%HOMEPATH%\android-sdks)
  • Now start Android-SDKs folder and run SDK manager

How do I create a shortcut via command-line in Windows?

I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.

@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo    Dim objShell,DesktopPath,objShortCut,MyTab
echo    Set objShell = CreateObject("WScript.Shell"^)
echo    MyTab = Split(ApplicationPath,"\"^)
echo    If Nom = "" Then
echo    Nom = MyTab(UBound(MyTab^)^)
echo    End if
echo    DesktopPath = objShell.SpecialFolders("Desktop"^)
echo    Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo    objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo    ObjShortCut.IconLocation = "Winver.exe,0"
echo    objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo    DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test 
Pause > Nul
::********************************************************************************************

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

How to sort mongodb with pymongo

TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().

Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:

  1. Using .find() and .sort().
  2. Or using the aggregation pipeline.

As suggested by many .find().sort() is the simplest way to perform the sorting.

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

However, this is a slow process compared to the aggregation pipeline.

Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:

  1. $match (optional step)
  2. $sort

NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.

Here's an example of the aggregation pipeline.

db.collection_name.aggregate([{
    "$match": {
        # your query - optional step
    }
},
{
    "$sort": {
        "field_1": pymongo.ASCENDING,
        "field_2": pymongo.DESCENDING,
        ....
    }
}])

Try this method yourself, compare the speed and let me know about this in the comments.

Edit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

I got the solution

download Xuggler 5.4 here

and some more jar to make it work...

commons-cli-1.1.jar

commons-lang-2.1.jar

logback-classic-1.0.0.jar

logback-core-1.0.0.jar

slf4j-api-1.6.4.jar

Reference Libraries

You can check which dependencies xuggler needs from here:

Add this jars and xuggle-xuggler-5.4.jar to your project's build path and it s ready.

**version numbers may change

How can I close a login form and show the main form without my application closing?

I would do this the other way round.

In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.

EDIT Code sample(s)

private void MainForm_Load(object sender, EventArgs e)
{
    this.Hide();

    LogonForm logon = new LogonForm();

    if (logon.ShowDialog() != DialogResult.OK)
    {
        //Handle authentication failures as necessary, for example:
        Application.Exit();
    }
    else
    {
        this.Show();
    }
}

Another solution would be to show the LogonForm from the Main method in program.cs, something like this:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    LogonForm logon = new LogonForm();

    Application.Run(logon);

    if (logon.LogonSuccessful)
    {
        Application.Run(new MainForm());
    }
}

In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials

Capitalize words in string

http://www.mediacollege.com/internet/javascript/text/case-capitalize.html is one of many answers out there.

Google can be all you need for such problems.

A naïve approach would be to split the string by whitespace, capitalize the first letter of each element of the resulting array and join it back together. This leaves existing capitalization alone (e.g. HTML stays HTML and doesn't become something silly like Html). If you don't want that affect, turn the entire string into lowercase before splitting it up.

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

How to use confirm using sweet alert?

You will need to prevent default form behaviour on submit. After that you will need to submit form programmatically in case of Ok button is selected.

Here is how it could look like:

document.querySelector('#from1').addEventListener('submit', function(e) {
  var form = this;

  e.preventDefault(); // <--- prevent form from submitting

  swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      icon: "warning",
      buttons: [
        'No, cancel it!',
        'Yes, I am sure!'
      ],
      dangerMode: true,
    }).then(function(isConfirm) {
      if (isConfirm) {
        swal({
          title: 'Shortlisted!',
          text: 'Candidates are successfully shortlisted!',
          icon: 'success'
        }).then(function() {
          form.submit(); // <--- submit form programmatically
        });
      } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
      }
    })
});

UPD. Example above uses sweetalert v2.x promise API.

Demo: http://plnkr.co/edit/YTY7PDs5Uh1XGUo9ic1s?p=preview

What are some resources for getting started in operating system development?

I found Robert Love's Linux Kernel Development quite interesting. It tells you about how the different subsystems in the Linux kernel works in a very down-to-earth way. Since the source is available Linux is a prime candidate for something to hack on.

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

How to echo out the values of this array?

var_dump($value)

it solved my problem, hope yours too.

How do getters and setters work?

Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.

package stackoverflow;

    public class StackoverFlow 

    {

        private int x;

        public int getX()
        {
            return x;
        }

        public int setX(int x)
        {
          return  this.x = x;
        }
         public void showX()
         {
             System.out.println("value of x  "+x);
         }


        public static void main(String[] args) {

            StackoverFlow sto = new StackoverFlow();
            sto.setX(10);
            sto.getX();
            sto.showX();
        }

    }

Hibernate: get entity by id

In getUserById you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user. Otherwise Hibernate.initialize(user); is actually Hibernate.initialize(null);

Here's the new getUserById (I haven't tested this ;)):

public User getUserById(Long user_id) {
    Session session = null;
    Object user = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        user = (User)session.load(User.class, user_id);
        Hibernate.initialize(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return user;
}

Character Limit in HTML

For the <input> element there's the maxlength attribute:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

(by the way, the type is "text", not "textbox" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.

Centering a Twitter Bootstrap button

Bootstrap have a specific class for this: center-block

<button type="button" class="your_class center-block"> Book </button>

Difference between no-cache and must-revalidate

With Jeffrey Fox's interpretation about no-cache, i've tested under chrome 52.0.2743.116 m, the result shows that no-cache has the same behavior as must-revalidate, they all will NOT use local cache when server is unreachable, and, they all will use cache while tap browser's Back/Forward button when server is unreachable. As above, i think max-age=0, must-revalidate is identical to no-cache, at least in implementation.

Elegant Python function to convert CamelCase to snake_case?

stringcase is my go-to library for this; e.g.:

>>> from stringcase import pascalcase, snakecase
>>> snakecase('FooBarBaz')
'foo_bar_baz'
>>> pascalcase('foo_bar_baz')
'FooBarBaz'

How to set a hidden value in Razor

If I understand correct you will have something like this:

<input value="default" id="sth" name="sth" type="hidden">

And to get it you have to write:

@Html.HiddenFor(m => m.sth, new { Value = "default" })

for Strongly-typed view.

How to prevent user from typing in text field without disabling the field?

Markup

<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
                                TabIndex="1">

Script

function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}