Programs & Examples On #Template specialization

Template specialization refers to programmer-generated explicit specialization of templates for specific types.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Uncaught TypeError: undefined is not a function while using jQuery UI

For my situation, it was a naming conflict problem. Adding $J solves it.

//Old code:
function () {
    var extractionDialog;

    extractionDialog = $j("#extractWindowDialog").dialog({
        autoOpen: false,
        appendTo: "form",
        height: "100",
        width: "250",
        modal: true
    });

    $("extractBomInfoBtn").button().on("click", function () {
        extractionDialog.dialog("open");
    }

And the following is new code.

 $j(function () {
    var extractionDialog;

    extractionDialog = $j("#extractWindowDialog").dialog({
        autoOpen: false,
        appendTo: "form",
        height: "100",
        width: "250",
        modal: true
    });

    $j("extractBomInfoBtn").button().on("click", function () {
        extractionDialog.dialog("open");
    });
});

Hope it could help someone.

Remove the last line from a file in Bash

echo -e '$d\nw\nq'| ed foo.txt

Git Diff with Beyond Compare

Please notice you make a wrong path of $2. because you are under Cygwin but BC3 not, so you should specify a full path for it. such as "d:/cygwin$2"

Please refer my git-diff-wrapper.sh here:

$ cat ~/git-diff-wrapper.sh
#!/bin/sh
echo $2
echo $5
/cygdrive/c/Program\ Files\ \(x86\)/Beyond\ Compare\ 3/BCompare.exe "d:/programs/cygwin$2" "$5"

Good luck.

Error: Argument is not a function, got undefined

If you are in a submodule, don't forget to declare the module in main app. ie :

<scrip>
angular.module('mainApp', ['subModule1', 'subModule2']);

angular.module('subModule1')
   .controller('MyController', ['$scope', function($scope) {
      $scope.moduleName = 'subModule1';
   }]);
</script>
...
<div ng-app="mainApp">
   <div ng-controller="MyController">
   <span ng-bind="moduleName"></span>
</div>

If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.

How do I grep recursively?

To find name of files with path recursively containing the particular string use below command for UNIX:

find . | xargs grep "searched-string"

for Linux:

grep -r "searched-string" .

find a file on UNIX server

find . -type f -name file_name

find a file on LINUX server

find . -name file_name

Invalid default value for 'create_date' timestamp field

That is because of server SQL Mode - NO_ZERO_DATE.

From the reference: NO_ZERO_DATE - In strict mode, don't allow '0000-00-00' as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.

How to keep :active css style after clicking an element

You can use a little bit of Javascript to add and remove CSS classes of your navitems. For starters, create a CSS class that you're going to apply to the active element, name it ie: ".activeItem". Then, put a javascript function to each of your navigation buttons' onclick event which is going to add "activeItem" class to the one activated, and remove from the others...

It should look something like this: (untested!)

/*In your stylesheet*/
.activeItem{
   background-color:#999; /*make some difference for the active item here */
}


/*In your javascript*/
var prevItem = null;
function activateItem(t){
   if(prevItem != null){
      prevItem.className = prevItem.className.replace(/{\b}?activeItem/, "");
   }
   t.className += " activeItem";
   prevItem = t;
}

<!-- And then your markup -->
<div id='nav'>
<a href='#abouts' onClick="activateItem(this)">
<div class='navitem about'>
about
</div>
</a>
<a href='#workss' onClick="activateItem(this)">
<div class='navitem works'>
works
</div>
</a>
</div>

Check if TextBox is empty and return MessageBox?

Adding on to what @tjg184 said, you could do something like...

if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim())) 

...

How to resolve git's "not something we can merge" error

I got this error when I did a git merge BRANCH_NAME "some commit message" - I'd forgotten to add the -m flag for the commit message, so it thought that the branch name included the comment.

How to get rid of the "No bootable medium found!" error in Virtual Box?

The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

GoogleTest: How to skip a test?

You can now use the GTEST_SKIP() macro to conditionally skip a test at runtime. For example:

TEST(Foo, Bar)
{
    if (blah)
        GTEST_SKIP();

    ...
}

Note that this is a very recent feature so you may need to update your GoogleTest library to use it.

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Send JSON data from Javascript to PHP?

PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.

In order to pass it as a string from Javascript, you can convert it to JSON using

JSON.stringify(object);

or a library such as Prototype

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

Google.com and clients1.google.com/generate_204

I found this old Thread while google'ing for generate_204 as Android seems to use this to determine if the wlan is open (response 204 is received) closed (no response at all) or blocked (redirect to captive portal is present). In that case a notification is shown that a log-in to WiFi is required...enter image description here

jquery beforeunload when closing (not leaving) the page?

Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?

Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.

var link_was_clicked = false;
document.addEventListener("click", function(e) {
   if (e.target.nodeName.toLowerCase() === 'a') {
      link_was_clicked = true;
   }
}, true);

window.onbeforeunload = function(e) {
    if(link_was_clicked) {
        return;
    }
    return confirm('Are you sure?');
}

Call Python function from JavaScript code

Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

'Class' does not contain a definition for 'Method'

If you are using a class from another project, the project needs to re-build and create re-the dll. Make sure "Build" is checked for that project on Build -> Configuration Manager in Visual Studio. So the reference project will re-build and update the dll.

Convert a Pandas DataFrame to a dictionary

Follow these steps:

Suppose your dataframe is as follows:

>>> df
   A  B  C ID
0  1  3  2  p
1  4  3  2  q
2  4  0  9  r

1. Use set_index to set ID columns as the dataframe index.

    df.set_index("ID", drop=True, inplace=True)

2. Use the orient=index parameter to have the index as dictionary keys.

    dictionary = df.to_dict(orient="index")

The results will be as follows:

    >>> dictionary
    {'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}

3. If you need to have each sample as a list run the following code. Determine the column order

column_order= ["A", "B", "C"] #  Determine your preferred order of columns
d = {} #  Initialize the new dictionary as an empty dictionary
for k in dictionary:
    d[k] = [dictionary[k][column_name] for column_name in column_order]

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

Here is how to build a function that returns a result set that can be queried as if it were a table:

SQL> create type emp_obj is object (empno number, ename varchar2(10));
  2  /

Type created.

SQL> create type emp_tab is table of emp_obj;
  2  /

Type created.

SQL> create or replace function all_emps return emp_tab
  2  is
  3     l_emp_tab emp_tab := emp_tab();
  4     n integer := 0;
  5  begin
  6     for r in (select empno, ename from emp)
  7     loop
  8        l_emp_tab.extend;
  9        n := n + 1;
 10       l_emp_tab(n) := emp_obj(r.empno, r.ename);
 11     end loop;
 12     return l_emp_tab;
 13  end;
 14  /

Function created.

SQL> select * from table (all_emps);

     EMPNO ENAME
---------- ----------
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7902 FORD
      7934 MILLER

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

If eclipse Java build path is mapped to 7, 8 and in Project pom.xml Maven properties java.version is mentioned higher Java version(9,10,11, etc..,) than 7,8 you need to update in pom.xml file.

In Eclipse if Java is mapped to Java version 11 and in pom.xml it is mapped to Java version 8. Update Eclipse support to Java 11 by go through below steps in eclipse IDE Help -> Install New Software ->

Paste following link http://download.eclipse.org/eclipse/updates/4.9-P-builds at Work With

or

Add (Popup window will open) ->

Name: Java 11 support Location: http://download.eclipse.org/eclipse/updates/4.9-P-builds

then update Java version in Maven properties of pom.xml file as below

<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>

Finally do right click on project Debug as -> Maven clean, Maven build steps

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

Import SQL file into mysql

I have installed my wamp server in D: drive so u have to go to the following path from ur command line->(and if u have installed ur wamp in c: drive then just replace the d: wtih c: here)

D:\>cd wamp
D:\wamp>cd bin
D:\wamp\bin>cd mysql
D:\wamp\bin\mysql>cd mysql5.5.8 (whatever ur verserion will be displayed here use keyboard Tab button)
D:\wamp\bin\mysql\mysql5.5.8>cd bin
D:\wamp\bin\mysql\mysql5.5.8\bin>mysql -u root -p password db_name < "d:\backupfile.sql"

here root is user of my phpmyadmin password is the password for phpmyadmin so if u haven't set any password for root just nothing type at that place, db_name is the database (for which database u r taking the backup) ,backupfile.sql is the file from which u want ur backup of ur database and u can also change the backup file location(d:\backupfile.sql) from to any other place on your computer

Multiple Where clauses in Lambda expressions

Can be

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty && l.InternalName != String.Empty)

or

x => x.Lists.Include(l => l.Title)
     .Where(l => l.Title != String.Empty)
     .Where(l => l.InternalName != String.Empty)

When you are looking at Where implementation, you can see it accepts a Func(T, bool); that means:

  • T is your IEnumerable type
  • bool means it needs to return a boolean value

So, when you do

.Where(l => l.InternalName != String.Empty)
//     ^                   ^---------- boolean part
//     |------------------------------ "T" part

LaTeX table too wide. How to make it fit?

You can use these options as well, either use \footnotesize or \tiny. This would really help in fitting big tables.

\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
    \toprule
    S.No       & HMD           \\
    \midrule
    1          & HTC Vive \\
    2          & HTC Vive Pro   \\
    \bottomrule
\end{tabular}
\end{table}

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Bootstrap-select - how to fire event on change

$("#Id").change(function(){
    var selected = $('#Id option:selected').val();
    alert(selected);           
});

I think this is what you need.

Access a function variable outside the function without using "global"

You could do something along this lines:

def static_example():
   if not hasattr(static_example, "static_var"):
       static_example.static_var = 0
   static_example.static_var += 1
   return static_example.static_var

print static_example()
print static_example()
print static_example()

Extract a part of the filepath (a directory) in Python

This is what I did to extract the piece of the directory:

for path in file_list:
  directories = path.rsplit('\\')
  directories.reverse()
  line_replace_add_directory = line_replace+directories[2]

Thank you for your help.

How to use HttpWebRequest (.NET) asynchronously?

By far the easiest way is by using TaskFactory.FromAsync from the TPL. It's literally a couple of lines of code when used in conjunction with the new async/await keywords:

var request = WebRequest.Create("http://www.stackoverflow.com");
var response = (HttpWebResponse) await Task.Factory
    .FromAsync<WebResponse>(request.BeginGetResponse,
                            request.EndGetResponse,
                            null);
Debug.Assert(response.StatusCode == HttpStatusCode.OK);

If you can't use the C#5 compiler then the above can be accomplished using the Task.ContinueWith method:

Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
                                    request.EndGetResponse,
                                    null)
    .ContinueWith(task =>
    {
        var response = (HttpWebResponse) task.Result;
        Debug.Assert(response.StatusCode == HttpStatusCode.OK);
    });

How to install PyQt4 in anaconda?

It looks like the latest version of anaconda forces install of pyqt5.6 over any pyqt build, which will be fatal for your applications. In a terminal, Try:

conda install -c anaconda pyqt=4.11.4

It will prompt to downgrade conda client. After that, it should be good.

UPDATE: If you want to know what pyqt versions are available for install, try:

conda search pyqt

UPDATE: The most recent version of conda installs anaconda-navigator. This depends on qt5, and should first be removed:

conda uninstall anaconda-navigator

Then install "newest" qt4:

conda install qt=4

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

How can I disable the UITableView selection?

The best solution would be Making The selection Style None

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

However, Here we are considering the fact that there are no custom images used for selected state.

How to declare a local variable in Razor?

you can put everything in a block and easily write any code that you wish in that block just exactly the below code :

@{
        bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
        if (isUserConnected)
        { // meaning that the viewing user has not been saved
            <div>
                <div> click to join us </div>
                <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
            </div>
        }
    }

it helps you to have at first a cleaner code and also you can prevent your page from loading many times different blocks of codes

Writing your own square root function

The following computes floor(sqrt(N)) for N > 0:

x = 2^ceil(numbits(N)/2)
loop:
    y = floor((x + floor(N/x))/2)
    if y >= x
        return x
    x = y

This is a version of Newton's method given in Crandall & Pomerance, "Prime Numbers: A Computational Perspective". The reason you should use this version is that people who know what they're doing have proven that it converges exactly to the floor of the square root, and it's simple so the probability of making an implementation error is small. It's also fast (although it's possible to construct an even faster algorithm -- but doing that correctly is much more complex). A properly implemented binary search can be faster for very small N, but there you may as well use a lookup table.

To round to the nearest integer, just compute t = floor(sqrt(4N)) using the algorithm above. If the least significant bit of t is set, then choose x = (t+1)/2; otherwise choose t/2. Note that this rounds up on a tie; you could also round down (or round to even) by looking at whether the remainder is nonzero (i.e. whether t^2 == 4N).

Note that you don't need to use floating-point arithmetic. In fact, you shouldn't. This algorithm should be implemented entirely using integers (in particular, the floor() functions just indicate that regular integer division should be used).

"Post Image data using POSTMAN"

That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.

What you should do is;

  1. After setting request method to POST, click to the 'body' tab.
  2. Select form-data. At first line, you'll see text boxes named key and value. Write 'image' to the key. You'll see value type which is set to 'text' as default. Make it File and upload your file.
  3. Then select 'raw' and paste your json file. Also just next to the binary choice, You'll see 'Text' is clicked. Make it JSON.

form-data section

raw section

You're ready to go.

In your Django view,

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes

@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):

    def post(self, request, format=None):
        thumbnail = request.FILES["file"]
        info = json.loads(request.data['info'])
        ...
        return HttpResponse()

How to read a string one letter at a time in python

For the actual processing I'd keep a string of finished product, and loop through each letter in the string they have entered. I'd call a function to convert a letter to morse code, then add it to the string of existing morse code.

finishedProduct = []
userInput = input("Enter text")
for letter in userInput:
    finishedProduct.append( letterToMorseCode(letter) )
theString = ''.join(finishedProduct)
print(theString)

You could either check for space in the loop, or in the function that is called.

How to echo or print an array in PHP?

To see the contents of array you can use.

1) print_r($array); or if you want nicely formatted array then:

echo '<pre>'; print_r($array); echo '</pre>';

2) use var_dump($array) to get more information of the content in the array like datatype and length.

3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website:
http://in3.php.net/manual/en/control-structures.foreach.php

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

How do I revert all local changes in Git managed project to previous state?

I searched for a similar issue,

Wanted to throw away local commits:

  1. cloned the repository (git clone)
  2. switched to dev branch (git checkout dev)
  3. did few commits (git commit -m "commit 1")
  4. but decided to throw away these local commits to go back to remote (origin/dev)

So did the below:

git reset --hard origin/dev

Check:

git status  

        On branch dev  
        Your branch is up-to-date with 'origin/dev'.  
        nothing to commit, working tree clean  

now local commits are lost, back to the initial cloned state, point 1 above.

HTTP requests and JSON parsing in Python

Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.

import json, requests, pprint

url = 'http://maps.googleapis.com/maps/api/directions/json?'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)


data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)

# test to see if the request was valid
#print output['status']

# output all of the results
#pprint.pprint(output)

# step-by-step directions
for route in output['routes']:
        for leg in route['legs']:
            for step in leg['steps']:
                print step['html_instructions']

Installing PG gem on OS X - failure to build native extension

For those who are not interested to use brew.

  1. Download PostgreSQL application.
  2. Follow the macOS default instruction to install it.
  3. It is advisable to run PostgreSQl.
  4. Run gem install pg -- --with-pg-config=/path/to/postgress/in/your/applications/folder/`
    • For example, in my machine it is /Applications/Postgres.app/Contents/Versions/12/bin/pg_config

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

How to merge remote changes at GitHub?

If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:

Switch to branch "foo" and update it:

$ git checkout foo
$ git pull

You can see the branches you've got by issuing command:

$ git branch

class << self idiom in Ruby

Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.

Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.

If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.

class Zen
end

z1 = Zen.new
z2 = Zen.new

class << z1
  def say_hello
    puts "Hello!"
  end
end

z1.say_hello    # Output: Hello!
z2.say_hello    # Output: NoMethodError: undefined method `say_hello'…

In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.

Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.

class Zabuton
  class << self
    def stuff
      puts "Stuffing zabuton…"
    end
  end
end

All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.

Additional info can be found at this post about Ruby Classes.

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

Is there any kind of hash code function in JavaScript?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

you can use Es6 symbol to create unique key and access object. Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

var obj = {};

obj[Symbol('a')] = 'a';
obj[Symbol.for('b')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

fill an array in C#

Say you want to fill with number 13.

int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

or

List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

if you prefer a list.

How do I get which JRadioButton is selected from a ButtonGroup

I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?

How to monitor network calls made from iOS Simulator

If you have cable connection and Mac, then there is simple and powerful method:

  1. install free Wireshark, make sure that it can capture devices with (and you need to do this after every computer restart!):

    sudo chmod 644 /dev/bpf*

  2. Now share your network with wifi. System preferences > Sharing > Internet Sharing. Check that you have "Share your connections from: Ethernet" and using: Wi-Fi. You may want to also to configure some wifi security, it does not disturb your data monitoring.

  3. Connect your phone to your newly created network. I need quite often several attempts here. If the phone does not want to connect, turn of wifi of Mac, then repeat step 2 above and be patient.

  4. Start Wireshark capture your wireless interface with Wireshark, it is probably "en1". Filter your needed IP addresses and/or ports. When you find a package which is interesting, select it, Right-click (context menu) > Follow TCP Stream and you see nice text representation of the requests and answers.

And what is the best: exactly the same trick works for Android also!

Where do I put image files, css, js, etc. in Codeigniter?

you can put the css folder inside the assest folder(you name it any name) in the directory of your project as:

- ci_app
- application 
- views      
- assets 
  - css 
    - style.css 

... when you want to load that file in a page, you can use base_url()function as this way: <head> <link rel='stylesheet' href='<?php echo base_url();?>assets/css/style.css'> </head> and you are sure to add base_url of your project in the config.php file as this:

$config['base_url'] = 'http://localhost/ci_app';

Table-level backup

Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.

EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg

Here are the steps from John Sansom's answer

How to Sort Multi-dimensional Array by Value?

One approach to achieve this would be like this

    $new = [
              [
                'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
                'title' => 'Flower',
                'order' => 3,
              ],

              [
                'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
                'title' => 'Free',
                'order' => 2,
              ],

              [
                'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
                'title' => 'Ready',
                'order' => 1,
              ],
    ];

    $keys = array_column($new, 'order');

    array_multisort($keys, SORT_ASC, $new);

    var_dump($new);

Result:

    Array
    (
        [0] => Array
            (
                [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
                [title] => Ready
                [order] => 1
            )

        [1] => Array
            (
                [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
                [title] => Free
                [order] => 2
            )

        [2] => Array
            (
                [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
                [title] => Flower
                [order] => 3
            )

    )

How to diff a commit with its parent?

git diff 15dc8 15dce~1

~1 means 'parent', ~2 'grandparent, etc.

Error when trying to access XAMPP from a network

This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185

Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin"> to have the following code:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

How do I add comments to package.json for npm install?

I have a funny hack idea.

Create an npm package name suitably as a comment divider for dependencies and devDependencies block in file package.json, for example x----x----x

{
    "name": "app-name",
    "dependencies": {
        "x----x----x": "this is the first line of a comment",
        "babel-cli": "6.x.x",
        "babel-core": "6.x.x",
        "x----x----x": "this is the second line of a comment",
        "knex": "^0.11.1",
        "mocha": "1.20.1",
        "x----x----x": "*"
    }
}

NOTE: You must add the last comment divider line with a valid version, like * in the block.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?

Have you tried simply creating this directory yourself, and restarting the service?

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

Generate random numbers with a given (numerical) distribution

Make a list of items, based on their weights:

items = [1, 2, 3, 4, 5, 6]
probabilities= [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
# if the list of probs is normalized (sum(probs) == 1), omit this part
prob = sum(probabilities) # find sum of probs, to normalize them
c = (1.0)/prob # a multiplier to make a list of normalized probs
probabilities = map(lambda x: c*x, probabilities)
print probabilities

ml = max(probabilities, key=lambda x: len(str(x)) - str(x).find('.'))
ml = len(str(ml)) - str(ml).find('.') -1
amounts = [ int(x*(10**ml)) for x in probabilities]
itemsList = list()
for i in range(0, len(items)): # iterate through original items
  itemsList += items[i:i+1]*amounts[i]

# choose from itemsList randomly
print itemsList

An optimization may be to normalize amounts by the greatest common divisor, to make the target list smaller.

Also, this might be interesting.

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

How to make an HTML back link?

you can try javascript

<A HREF="javascript:history.go(-1)">

refer JavaScript Back Button

EDIT

to display url of refer http://www.javascriptkit.com/javatutors/crossmenu2.shtml

and send the element a itself in onmouseover as follow

_x000D_
_x000D_
function showtext(thetext) {_x000D_
  if (!document.getElementById)_x000D_
    return_x000D_
  textcontainerobj = document.getElementById("tabledescription")_x000D_
  browserdetect = textcontainerobj.filters ? "ie" : typeof textcontainerobj.style.MozOpacity == "string" ? "mozilla" : ""_x000D_
  instantset(baseopacity)_x000D_
  document.getElementById("tabledescription").innerHTML = thetext.href_x000D_
  highlighting = setInterval("gradualfade(textcontainerobj)", 50)_x000D_
}
_x000D_
 <a href="http://www.javascriptkit.com" onMouseover="showtext(this)" onMouseout="hidetext()">JavaScript Kit</a>
_x000D_
_x000D_
_x000D_

check jsfiddle

Format XML string to print friendly XML string

Check the following link: How to pretty-print XML (Unfortunately, the link now returns 404 :()

The method in the link takes an XML string as an argument and returns a well-formed (indented) XML string.

I just copied the sample code from the link to make this answer more comprehensive and convenient.

public static String PrettyPrint(String XML)
{
    String Result = "";

    MemoryStream MS = new MemoryStream();
    XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
    XmlDocument D   = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        D.LoadXml(XML);

        W.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        D.WriteContentTo(W);
        W.Flush();
        MS.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        MS.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader SR = new StreamReader(MS);

        // Extract the text from the StreamReader.
        String FormattedXML = SR.ReadToEnd();

        Result = FormattedXML;
    }
    catch (XmlException)
    {
    }

    MS.Close();
    W.Close();

    return Result;
}

scrollTop jquery, scrolling to div with id?

if you want to scroll just only some div, can use the div id instead of 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...

PHP move_uploaded_file() error?

In php.ini search for upload_max_filesize and post_max_size. I had the same problem and the solution was to change these values to a value greater than the file size.

Linux Command History with date and time

In case you are using zsh you can use for example the -E or -i switch:

history -E

If you do a man zshoptions or man zshbuiltins you can find out more information about these switches as well as other info related to history:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

How can I hide or encrypt JavaScript code?

JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.

The only way to partially hide it, at least from the less technical minds, is to obfuscate.

Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

How to break lines in PowerShell?

Try "`n" with double quotes. (not single quotes '`n' )

For a complete list of escaping characters see:

Help about_Escape_character

The code should be

$str += "`n"

How to automatically generate a stacktrace when my program crashes

ulimit -c unlimited

is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!

regards

Vue.js data-bind style backgroundImage not working

Based on my knowledge, if you put your image folder in your public folder, you can just do the following:

   <div :style="{backgroundImage: `url(${project.imagePath})`}"></div>

If you put your images in the src/assets/, you need to use require. Like this:

   <div :style="{backgroundImage: 'url('+require('@/assets/'+project.image)+')'}">. 
   </div>

One important thing is that you cannot use an expression that contains the full URL like this project.image = '@/assets/image.png'. You need to hardcode the '@assets/' part. That was what I've found. I think the reason is that in Webpack, a context is created if your require contains expressions, so the exact module is not known on compile time. Instead, it will search for everything in the @/assets folder. More info could be found here. Here is another doc explains how the Vue loader treats the link in single file components.

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

Based on the documentation the origin parameter is optional and it defaults to the user's location.

... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....

ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling

For me this works on Desktop, IOS and Android.

Open a link in browser with java button?

I know that this is an old question but sometimes the Desktop.getDesktop() produces an unexpected crash like in Ubuntu 18.04. Therefore, I have to re-write my code like this:

public static void openURL(String domain)
{
    String url = "https://" + domain;
    Runtime rt = Runtime.getRuntime();
    try {
        if (MUtils.isWindows()) {
            rt.exec("rundll32 url.dll,FileProtocolHandler " + url).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isMac()) {
            String[] cmd = {"open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isUnix()) {
            String[] cmd = {"xdg-open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else {
            try {
                throw new IllegalStateException();
            } catch (IllegalStateException e1) {
                MUtils.alertMessage(Lang.get("desktop.not.supported"), MainPn.getMainPn());
                e1.printStackTrace();
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

public static boolean isWindows()
{
    return OS.contains("win");
}

public static boolean isMac()
{
    return OS.contains("mac");
}

public static boolean isUnix()
{
    return OS.contains("nix") || OS.contains("nux") || OS.indexOf("aix") > 0;
}

Then we can call this helper from the instance:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MUtils.openURL("www.google.com"); // just what is the 'open' method?
    }
});

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!

How to Publish Web with msbuild?

You must set your environments

  • < WebSite name>
  • < domain>

and reference my blog.(sorry post was Korean)

  • http://xyz37.blog.me/50124665657
  • http://blog.naver.com/PostSearchList.nhn?SearchText=webdeploy&blogId=xyz37&x=25&y=7

    @ECHO OFF
    :: http://stackoverflow.com/questions/5598668/valid-parameters-for-msdeploy-via-msbuild
    ::-DeployOnBuild -True
    :: -False
    :: 
    ::-DeployTarget -MsDeployPublish
    :: -Package
    :: 
    ::-Configuration -Name of a valid solution configuration
    :: 
    ::-CreatePackageOnPublish -True
    :: -False
    :: 
    ::-DeployIisAppPath -<Web Site Name>/<Folder>
    :: 
    ::-MsDeployServiceUrl -Location of MSDeploy installation you want to use
    :: 
    ::-MsDeployPublishMethod -WMSVC (Web Management Service)
    :: -RemoteAgent
    :: 
    ::-AllowUntrustedCertificate (used with self-signed SSL certificates) -True
    :: -False
    :: 
    ::-UserName
    ::-Password
    SETLOCAL
    
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v3.5" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v3.5"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v4.0.30319" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319"
    
    SET targetFile=<web site fullPath ie. .\trunk\WebServer\WebServer.csproj
    SET configuration=Release
    SET msDeployServiceUrl=https://<domain>:8172/MsDeploy.axd
    SET msDeploySite="<WebSite name>"
    SET userName="WebDeploy"
    SET password=%USERNAME%
    SET platform=AnyCPU
    SET msbuild=%FXPath%\MSBuild.exe /MaxCpuCount:%NUMBER_OF_PROCESSORS% /clp:ShowCommandLine
    
    %MSBuild% %targetFile% /p:configuration=%configuration%;Platform=%platform% /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=False /p:DeployIISAppPath=%msDeploySite% /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=%msDeployServiceUrl% /p:AllowUntrustedCertificate=True /p:UserName=%USERNAME% /p:Password=%password% /p:SkipExtraFilesOnServer=True /p:VisualStudioVersion=12.0
    
    IF NOT "%ERRORLEVEL%"=="0" PAUSE 
    ENDLOCAL
    

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

OK so I think i know the issue you're having.

Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.

How to fix it (possibly) You need to add some extra information to your composer.json file.

"autoload": {
    "classmap": [
        "PATH TO YOUR MIGRATIONS FOLDER"
    ],
}

You need to add the path to your migrations folder to the classmap array. Then run the following three commands...

php artisan clear-compiled 
composer dump-autoload
php artisan optimize

This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.

Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).

Hope you can manage to get this sorted, as its very annoying indeed :(

How to style the menu items on an Android action bar

You have to change

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">

to

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Menu">

as well. This works for me.

A general tree implementation?

A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

Then interact:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
...   print c.data
... 
6
7
>>> 

This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.

How to close a JavaFX application on window close?

This seemed to work for me:

EventHandler<ActionEvent> quitHandler = quitEvent -> {

        System.exit(0);

    };
    // Set the handler on the Start/Resume button
    quit.setOnAction(quitHandler);

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

How to run a single RSpec test?

In rails 5,

I used this way to run single test file(all the tests in one file)

rails test -n /TopicsControllerTest/ -v

Class name can be used to match to the desired file TopicsControllerTest

My class class TopicsControllerTest < ActionDispatch::IntegrationTest

Output :

enter image description here

If You want you can tweak the regex to match to single test method \TopicsControllerTest#test_Should_delete\

rails test -n /TopicsControllerTest#test_Should_delete/ -v

How to see indexes for a database or table in MySQL?

This works in my case for getting table name and column name in the corresponding table for indexed fields.

SELECT TABLE_NAME , COLUMN_NAME, COMMENT 
FROM information_schema.statistics
WHERE table_schema = 'database_name';

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

Oracle query to fetch column names

You may try this : ( It works on 11g and it returns all column name from a table , here test_tbl is the table name and user_tab_columns are user permitted table's columns )

select  COLUMN_NAME  from user_tab_columns
where table_name='test_tbl'; 

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

Had the same issue, the reason for it was BCrypt.Net library, compiled using .NET 2.0 framework, while the whole project, which used it, was compiling with .NET 4.0. If symptoms are the same, try download BCrypt source code and rebuild it in release configuration within .NET 4.0. After I'd done it "pre-login handshake" worked fine. Hope it helps anyone.

How to get a list column names and datatypes of a table in PostgreSQL?

SELECT
        a.attname as "Column",
        pg_catalog.format_type(a.atttypid, a.atttypmod) as "Datatype"
    FROM
        pg_catalog.pg_attribute a
    WHERE
        a.attnum > 0
        AND NOT a.attisdropped
        AND a.attrelid = (
            SELECT c.oid
            FROM pg_catalog.pg_class c
                LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relname ~ '^(hello world)$'
                AND pg_catalog.pg_table_is_visible(c.oid)
        );

Change the hello world with your table name

More info on it : http://www.postgresql.org/docs/9.3/static/catalog-pg-attribute.html

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

React / JSX Dynamic Component Name

Across all options with component maps I haven't found the simplest way to define the map using ES6 short syntax:

import React from 'react'
import { PhotoStory, VideoStory } from './stories'

const components = {
    PhotoStory,
    VideoStory,
}

function Story(props) {
    //given that props.story contains 'PhotoStory' or 'VideoStory'
    const SpecificStory = components[props.story]
    return <SpecificStory/>
}

How to take complete backup of mysql database using mysqldump command line utility

To create dump follow below steps:

  1. Open CMD and go to bin folder where you have installed your MySQL
    ex:C:\Program Files\MySQL\MySQL Server 8.0\bin. If you see in this
    folder mysqldump.exe will be there. Or you have setup above folder in your Path variable of Environment Variable.

  2. Now if you hit mysqldump in CMD you can see CMD is able to identify dump command.

  3. Now run "mysqldump -h [host] -P [port] -u [username] -p --skip-triggers --no-create-info --single-transaction --quick --lock-tables=false ABC_databse > c:\xyz.sql"
  4. Above command will prompt for password then it will start processing.

Convert int to ASCII and back in Python

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

MongoDb query condition on comparing 2 fields

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

Regular Query:

db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})

Aggregation Query:

db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

In Chrome (v.56 is what I'm using but I AFAIK this applies generally) you can set title=" " (a single space) and the automatic title text will be overridden and nothing displayed. (If you try to make it just an empty string, though, it will treat it as if it isn't set and add that automatic tooltip text you've been getting).

I haven't tested this in other browsers, because I found it whilst making a Google Chrome Extension. I'm sure once I port things to other browsers, though, I'll see if it works in them (if even necessary), too.

How to write files to assets folder or raw folder in android?

Another approach for same issue may help you Read and write file in private context of application

                 String NOTE = "note.txt";  
                 private void writeToFile() {
        try {
         OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
                NOTES, 0));

         out.write("testing");
         out.close();
         }

        catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
        }
             }


           private void ReadFromFile()
      {
        try {
        InputStream in = openFileInput(NOTES);
        if (in != null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(tmp);
            String str;
            StringBuffer buf = new StringBuffer();
            while ((str = reader.readLine()) != null) {
                buf.append(str + "\n");
            }
            in.close();
            String temp = "Not Working";
            temp = buf.toString();
            Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
        }
    } catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    } catch (Throwable t) {
        Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    }
}

How do I prevent people from doing XSS in Spring MVC?

Instead of relying only on <c:out />, an antixss library should also be used, which will not only encode but also sanitize malicious script in input. One of the best library available is OWASP Antisamy, it's highly flexible and can be configured(using xml policy files) as per requirement.

For e.g. if an application supports only text input then most generic policy file provided by OWASP can be used which sanitizes and removes most of the html tags. Similarly if application support html editors(such as tinymce) which need all kind of html tags, a more flexible policy can be use such as ebay policy file

How to execute 16-bit installer on 64-bit Win7?

16 bit installer will not work on windows 7 it's no longer supported by win 7 the most recent supported version of windows that can run 16 bit installer is vista 32-bit even vista 64-bit doesn't support 16-bit installer.... reference http://support.microsoft.com/kb/946765

HTML if image is not found

I wanted to hide the space occupied by <img> tag so this worked for me

<img src = "source.jpg" alt = "" >

Recommended method for escaping HTML in Java

While @dfa answer of org.apache.commons.lang.StringEscapeUtils.escapeHtml is nice and I have used it in the past it should not be used for escaping HTML (or XML) attributes otherwise the whitespace will be normalized (meaning all adjacent whitespace characters become a single space).

I know this because I have had bugs filed against my library (JATL) for attributes where whitespace was not preserved. Thus I have a drop in (copy n' paste) class (of which I stole some from JDOM) that differentiates the escaping of attributes and element content.

While this may not have mattered as much in the past (proper attribute escaping) it is increasingly become of greater interest given the use use of HTML5's data- attribute usage.

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

Extracting text OpenCV

Python Implementation for @dhanushka's solution:

def process_rgb(rgb):
    hasText = False
    gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
    morphKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
    grad = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, morphKernel)
    # binarize
    _, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    # connect horizontally oriented regions
    morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morphKernel)
    # find contours
    mask = np.zeros(bw.shape[:2], dtype="uint8")
    _,contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    # filter contours
    idx = 0
    while idx >= 0:
        x,y,w,h = cv2.boundingRect(contours[idx])
        # fill the contour
        cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)
        # ratio of non-zero pixels in the filled region
        r = cv2.contourArea(contours[idx])/(w*h)
        if(r > 0.45 and h > 5 and w > 5 and w > h):
            cv2.rectangle(rgb, (x,y), (x+w,y+h), (0, 255, 0), 2)
            hasText = True
        idx = hierarchy[0][idx][0]
    return hasText, rgb

Using BigDecimal to work with currencies

I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.

public class Money {

    private static final Currency USD = Currency.getInstance("USD");
    private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;

    private final BigDecimal amount;
    private final Currency currency;   

    public static Money dollars(BigDecimal amount) {
        return new Money(amount, USD);
    }

    Money(BigDecimal amount, Currency currency) {
        this(amount, currency, DEFAULT_ROUNDING);
    }

    Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
        this.currency = currency;      
        this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public Currency getCurrency() {
        return currency;
    }

    @Override
    public String toString() {
        return getCurrency().getSymbol() + " " + getAmount();
    }

    public String toString(Locale locale) {
        return getCurrency().getSymbol(locale) + " " + getAmount();
    }   
}

Coming to the usage:

You would represent all monies using Money object as opposed to BigDecimal. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money pattern you centralize the formatting of money to a single location.

Money price = Money.dollars(38.28);
System.out.println(price);

react-router scroll to top on every transition

It is noteable that the onUpdate={() => window.scrollTo(0, 0)} method is outdated.

Here is a simple solution for react-router 4+.

const history = createBrowserHistory()

history.listen(_ => {
    window.scrollTo(0, 0)  
})

<Router history={history}>

What does void mean in C, C++, and C#?

It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.

ProgressDialog in AsyncTask

Fixed by moving the view modifiers to onPostExecute so the fixed code is :

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        new ProgressTask(Soirees.this).execute();


   }


    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        List<Message> titles;
        private ListActivity activity;
        //private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }



        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

            @Override
        protected void onPostExecute(final Boolean success) {
                List<Message> titles = new ArrayList<Message>(messages.size());
                for (Message msg : messages){
                    titles.add(msg);
                }
                MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                activity.setListAdapter(adapter);
                adapter.notifyDataSetChanged();

                if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try{    
                BaseFeedParser parser = new BaseFeedParser();
                messages = parser.parse();


                return true;
             } catch (Exception e){
                Log.e("tag", "error", e);
                return false;
             }
          }


    }

}

@Vladimir, thx your code was very helpful.

How to convert all tables in database to one collation?

You need to execute a alter table statement for each table. The statement would follow this form:

ALTER TABLE tbl_name
[[DEFAULT] CHARACTER SET charset_name]
[COLLATE collation_name]

Now to get all the tables in the database you would need to execute the following query:

SELECT * 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDataBaseName"
AND TABLE_TYPE="BASE TABLE";

So now let MySQL write the code for you:

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE your_collation_name_here;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDatabaseName"
AND TABLE_TYPE="BASE TABLE";

You can copy the results and execute them. I have not tested the syntax but you should be able to figure out the rest. Think of it as a little exercise.

Hope That Helps!

jQuery: Best practice to populate drop down?

I have been using jQuery and calling a function to populate drop downs.

function loadDropDowns(name,value)
{
   var ddl = "#Categories";
   $(ddl).append('<option value="' + value + '">' + name + "</option>'");
}

Fill remaining vertical space - only CSS

You can just add the overflow:auto option:

#second
{
   width:300px;
   height:100%;
   overflow: auto;
   background-color:#9ACD32;
}

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

How can I list all of the files in a directory with Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );

exit;

sub wanted {
  push @content, $File::Find::name;
  return;
}

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

Compute mean and standard deviation by group for multiple variables in a data.frame

Here's another take on the data.table answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply instead of sapply):

library(data.table)
set.seed(1)
dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
#   ID mean.Obs_1 mean.Obs_2 mean.Obs_3  sd.Obs_1  sd.Obs_2  sd.Obs_3
#1:  1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
#2:  2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
#3:  3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

What is a callback?

A callback is a function that will be called when a process is done executing a specific task.

The usage of a callback is usually in asynchronous logic.

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.

    public delegate void WorkCompletedCallBack(string result);

    public void DoWork(WorkCompletedCallBack callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
        DoWork(callback);
    }

    public void TestCallBack(string result)
    {
        Console.WriteLine(result);
    }

In today C#, this could be done using lambda like:

    public void DoWork(Action<string> callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        DoWork((result) => Console.WriteLine(result));
    }

Mockito How to mock and assert a thrown exception?

Make the exception happen like this:

when(obj.someMethod()).thenThrow(new AnException());

Verify it has happened either by asserting that your test will throw such an exception:

@Test(expected = AnException.class)

Or by normal mock verification:

verify(obj).someMethod();

The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

How to hide "Showing 1 of N Entries" with the dataTables.js library

Now, this seems to work:

$('#example').DataTable({
  "info": false
});

it hides that div, altogether

JQUERY ajax passing value from MVC View to Controller

[HttpPost]
public ActionResult SaveComments(int id, string comments){
     var actions = new Actions(User.Identity.Name);
     var status = actions.SaveComments(id, comments);
     return Content(status);
}

Difference between private, public, and protected inheritance

I found an easy answer and so thought of posting it for my future reference too.

Its from the links http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};

class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:

        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};

int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}

Proper usage of .net MVC Html.CheckBoxFor

I was looking for the solution to show the label dynamically from database like this:

checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database

So none of the above solution worked for me so I used like this:

 @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
 <label for="Option1">@Model.Option1Text</label>

 @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
 <label for="Option2">@Mode2.Option1Text</label>

In this way when user will click on label, checkbox will be selected.

Might be it can help someone.

How to use class from other files in C# with visual studio?

I was having the same problem here. Found out that the problem was with an Advanced Property of the file. There is there an option with the name 'Compilation Action' (may be not with the exact words, I am translating - my VS is in Portuguese).

My Class1.cs file was there as "Content" and I just had to change it to "Compile" to make it work, and have the classes recognized by the others files in the same project.

Jenkins: Failed to connect to repository

In my case, I edited the known_hosts file with root user. So it changed the file ownership to root and jenkins user started throwing "[email protected]:xxxxxx/xxxx.git HEAD" returned status code 128: stdout: stderr: Host key verification failed" error while cloning git image. Reverting the ownership resolved the issue.

how to create inline style with :before and :after

You can't. With inline styles you are targeting the element directly. You can't use other selectors there.

What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.

Save Javascript objects in sessionStorage

You can create 2 wrapper methods for saving and retrieving object from session storage.

function saveSession(obj) {
  sessionStorage.setItem("myObj", JSON.stringify(obj));
  return true;
}

function getSession() {
  var obj = {};
  if (typeof sessionStorage.myObj !== "undefined") {
    obj = JSON.parse(sessionStorage.myObj);
  }
  return obj;
}

Use it like this:- Get object, modify some data, and save back.

var obj = getSession();

obj.newProperty = "Prod"

saveSession(obj);

How to retrieve unique count of a field using Kibana + Elastic Search

Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

Compile to a stand-alone executable (.exe) in Visual Studio

I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.

But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.

How to make a radio button unchecked by clicking it?

I came here because I had the same issue. I wanted to present the options to the user while leaving the option of remaining empty. Although this is possible to explicitly code using checkboxes that would complicate the back end.

Having the user Control+click is almost as good as having them uncheck it through the console. Catching the mousedown is to early and onclick is too late.

Well, at last here is a solution! Just put these few lines once on the page and you have it made for all radio buttons on the page. You can even fiddle with the selector to customize it.

_x000D_
_x000D_
window.onload = function() {_x000D_
  document.querySelectorAll("INPUT[type='radio']").forEach(function(rd) {_x000D_
    rd.addEventListener("mousedown", function() {_x000D_
      if(this.checked) {_x000D_
        this.onclick=function() {_x000D_
          this.checked=false_x000D_
        }_x000D_
      } else {_x000D_
        this.onclick=null_x000D_
      }_x000D_
    })_x000D_
  })_x000D_
}
_x000D_
<input type=radio name=unchecksample> Number One<br>_x000D_
<input type=radio name=unchecksample> Number Two<br>_x000D_
<input type=radio name=unchecksample> Number Three<br>_x000D_
<input type=radio name=unchecksample> Number Four<br>_x000D_
<input type=radio name=unchecksample> Number Five<br>
_x000D_
_x000D_
_x000D_

How do you check whether a number is divisible by another number (Python)?

You do this using the modulus operator, %

n % k == 0

evaluates true if and only if n is an exact multiple of k. In elementary maths this is known as the remainder from a division.

In your current approach you perform a division and the result will be either

  • always an integer if you use integer division, or
  • always a float if you use floating point division.

It's just the wrong way to go about testing divisibility.

Select data between a date/time range

You can either user STR_TO_DATE function and pass your own date parameters based on the format you have posted :

select * from hockey_stats where game_date 
  between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
  and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s') 
order by game_date desc;

Or just use the format which MySQL handles dates YYYY:MM:DD HH:mm:SS and have the query as

select * from hockey_stats where game_date between '2012-03-11 00:00:00' and'2012-05-11 23:59:00' order by game_date desc;

How do I store an array in localStorage?

The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.

at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).

How do I check if there are duplicates in a flat list?

def check_duplicates(my_list):
    seen = {}
    for item in my_list:
        if seen.get(item):
            return True
        seen[item] = True
    return False

How to make IPython notebook matplotlib plot inline

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Calculate time difference in Windows batch file

Using a single function with the possibility of custom unit of measure or formatted. Each time the function is called without parameters we restarted the initial time.

@ECHO OFF

ECHO.
ECHO DEMO timer function
ECHO --------------------

SET DELAY=4

:: First we call the function without any parameters to set the starting time
CALL:timer

:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.

ping -n %DELAY% -w 1 127.0.0.1 >NUL

:: Now we call the function again with the desired parameters

CALL:timer elapsed_time

ECHO by Default : %elapsed_time%

CALL:timer elapsed_time "s"

ECHO in Seconds : %elapsed_time%

CALL:timer elapsed_time "anything"

ECHO Formatted  : %elapsed_time%  (HH:MM:SS.CS)

ECHO.
PAUSE


:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters 
:: to be in another unit of measure or with formatted
::
::  Parameters:
::             <return>     the returned value
::             [formatted]  s (for seconds), m (for minutes), h (for hours)
::                          anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
    SetLocal EnableExtensions EnableDelayedExpansion

    SET _t=%time%
    SET _t=%_t::0=: %
    SET _t=%_t:,0=, %
    SET _t=%_t:.0=. %
    SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
    SET /A _t=%_t%

    :: If we call the function without parameters is defined initial time
    SET _r=%~1
    IF NOT DEFINED _r (
        EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
    )

    SET /A _t=%_t% - %TIMER_START_TIME%

    :: In the case of wanting a formatted output
    SET _f=%~2
    IF DEFINED _f (

        IF "%_f%" == "s" (

            SET /A "_t=%_t% / 100"

        ) ELSE (
            IF "%_f%" == "m" (

                SET /A "_t=%_t% / 6000"

            ) ELSE (

                IF "%_f%" == "h" (

                    SET /A "_t=%_t% / 360000"

                ) ELSE (

                    SET /A "_h=%_t% / 360000"
                    SET /A "_m=(%_t% - !_h! * 360000) / 6000"
                    SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
                    SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"

                    IF !_h! LSS 10 SET "_h=0!_h!"
                    IF !_m! LSS 10 SET "_m=0!_m!"
                    IF !_s! LSS 10 SET "_s=0!_s!"
                    IF !_cs! LSS 10 SET "_cs=0!_cs!"
                    SET "_t=!_h!:!_m!:!_s!.!_cs!"
                    SET "_t=!_t:00:=!"

                )
            )
        )
    )

    EndLocal & SET %~1=%_t%
goto :EOF

A test with a delay of 94 sec

DEMO timer function
--------------------

Making some delay, please wait...

by Default : 9404
in Seconds : 94
Formatted  : 01:34.05  (HH:MM:SS.CS)

Presione una tecla para continuar . . .

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How to combine multiple inline style objects?

I have built an module for this if you want to add styles based on a condition like this:

multipleStyles(styles.icon, { [styles.iconRed]: true })

https://www.npmjs.com/package/react-native-multiple-styles

How do I clear only a few specific objects from the workspace?

  1. In RStudio, ensure the Environment tab is in Grid (not List) mode.

  2. Tick the object(s) you want to remove from the environment.

  3. Click the broom icon.

How can I keep Bootstrap popovers alive while being hovered?

Vikas answer works perfectly for me, here I also add support for the delay (show / hide).

var popover = $('#example');
var options = {
    animation : true,
    html: true,
    trigger: 'manual',
    placement: 'right',
    delay: {show: 500, hide: 100}
};   
popover
    .popover(options)
    .on("mouseenter", function () {

        var t = this;
        var popover = $(this);    
        setTimeout(function () {

            if (popover.is(":hover")) {

                popover.popover("show");
                popover.siblings(".popover").on("mouseleave", function () {
                    $(t).popover('hide');
                });
            }
        }, options.delay.show);
    })
    .on("mouseleave", function () {
        var t = this;
        var popover = $(this);

        setTimeout(function () {
            if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
                $(t).popover("hide")
            }
        }, options.delay.hide);
    });     

Also please pay attention I changed:

if (!$(".popover:hover").length) {

with:

if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {

so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)

Java output formatting for Strings

If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

How to dynamically remove items from ListView on a button click?

adapter.remove(arraylist.get(position));
adapter.notifyDataSetChanged();

or you can call again

setListAdapter(adapter)

Best practices for API versioning?

We found it practical and useful to put the version in the URL. It makes it easy to tell what you're using at a glance. We do alias /foo to /foo/(latest versions) for ease of use, shorter / cleaner URLs, etc, as the accepted answer suggests.

Keeping backwards compatibility forever is often cost-prohibitive and/or very difficult. We prefer to give advanced notice of deprecation, redirects like suggested here, docs, and other mechanisms.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

While many of the above answers are completely valid, no one seems to answer your question completely, specifically the part:

I don't know if I am right, but to determine probabilities I think I need to fit my data to a theoretical distribution that is the most suitable to describe my data. I assume that some kind of goodness of fit test is needed to determine the best model.

The parametric approach

This is the process you're describing of using some theoretical distribution and fitting the parameters to your data and there's some excellent answers how to do this.

The non-parametric approach

However, it's also possible to use a non-parametric approach to your problem, which means you do not assume any underlying distribution at all.

By using the so-called Empirical distribution function which equals: Fn(x)= SUM( I[X<=x] ) / n. So the proportion of values below x.

As was pointed out in one of the above answers is that what you're interested in is the inverse CDF (cumulative distribution function), which is equal to 1-F(x)

It can be shown that the empirical distribution function will converge to whatever 'true' CDF that generated your data.

Furthermore, it is straightforward to construct a 1-alpha confidence interval by:

L(X) = max{Fn(x)-en, 0}
U(X) = min{Fn(x)+en, 0}
en = sqrt( (1/2n)*log(2/alpha)

Then P( L(X) <= F(X) <= U(X) ) >= 1-alpha for all x.

I'm quite surprised that PierrOz answer has 0 votes, while it's a completely valid answer to the question using a non-parametric approach to estimating F(x).

Note that the issue you mention of P(X>=x)=0 for any x>47 is simply a personal preference that might lead you to chose the parametric approach above the non-parametric approach. Both approaches however are completely valid solutions to your problem.

For more details and proofs of the above statements I would recommend having a look at 'All of Statistics: A Concise Course in Statistical Inference by Larry A. Wasserman'. An excellent book on both parametric and non-parametric inference.

EDIT: Since you specifically asked for some python examples it can be done using numpy:

import numpy as np

def empirical_cdf(data, x):
    return np.sum(x<=data)/len(data)

def p_value(data, x):
    return 1-empirical_cdf(data, x)

# Generate some data for demonstration purposes
data = np.floor(np.random.uniform(low=0, high=48, size=30000))

print(empirical_cdf(data, 20))
print(p_value(data, 20)) # This is the value you're interested in

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

Python string prints as [u'String']

Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText

        avail = []
        avail = driver.find_elements_by_class_name("label");
        for i in avail:
                if  i.text == "MyText":

Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?

Storing Objects in HTML5 localStorage

I made another minimalistic wrapper with only 20 lines of code to allow using it like it should:

localStorage.set('myKey',{a:[1,2,5], b: 'ok'});
localStorage.has('myKey');   // --> true
localStorage.get('myKey');   // --> {a:[1,2,5], b: 'ok'}
localStorage.keys();         // --> ['myKey']
localStorage.remove('myKey');

https://github.com/zevero/simpleWebstorage

Django, creating a custom 500/404 error page

In Django 2.* you can use this construction in views.py

def handler404(request, exception):
    return render(request, 'errors/404.html', locals())

In settings.py

DEBUG = False

if DEBUG is False:
    ALLOWED_HOSTS = [
        '127.0.0.1:8000',
        '*',
    ]

if DEBUG is True:
    ALLOWED_HOSTS = []

In urls.py

# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'

Usually i creating default_app and handle site-wide errors, context processors in it.

How to find time complexity of an algorithm

O(n) is big O notation used for writing time complexity of an algorithm. When you add up the number of executions in an algoritm you'll get an expression in result like 2N+2, in this expression N is the dominating term(the term having largest effect on expression if its value increases or decreases). Now O(N) is the time comlexity while N is dominating term. Example

For i= 1 to n;
  j= 0;
while(j<=n);
  j=j+1;

here total number of executions for inner loop are n+1 and total number of executions for outer loop are n(n+1)/2, so total number of executions for whole algorithm are n+1+n(n+1/2) = (n^2+3n)/2. here n^2 is the dominating term so the time complexity for this algorithm is O(n^2)

Is it possible to change the speed of HTML's <marquee> tag?

To increase scroll speed of text use attribute

scrollamount
OR
scrolldelay

in the 'marquee' tag. place any integer value which represent how fast you need your text to move

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

initializing a Guava ImmutableMap

if the map is short you can do:

ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs

If it is longer then:

ImmutableMap.builder()
   .put(key, value)
   .put(key2, value2)
   // ...
   .build();

Java: how do I initialize an array size if it's unknown?

I think you need use List or classes based on that.

For instance,

ArrayList<Integer> integers = new ArrayList<Integer>();
int j;

do{
    integers.add(int.nextInt());
    j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );

You could read this article for getting more information about how to use that.

How to list all Git tags?

Also git show-ref is rather useful, so that you can directly associate tags with correspondent commits:

$ git tag
osgeolive-6.5
v8.0
...

$ git show-ref --tags
e7e66977c1f34be5627a268adb4b9b3d59700e40 refs/tags/osgeolive-6.5
8f27e65bddd7d4b8515ce620fb485fdd78fcdf89 refs/tags/v8.0
...

How to set value of input text using jQuery

this is for classes

$('.nameofdiv').val('we are developers');

for ids

$('#nameofdiv').val('we are developers');

now if u have an iput in a form u can use

$("#form li.name input.name_val").val('we are awsome developers');

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

TypeError: 'list' object cannot be interpreted as an integer

You should do this instead:

for i in myList:
    # etc.

That is, remove the range() part. The range() function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.

Java Timer vs ExecutorService?

If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();

will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

  • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
  • The 'one off' executions can return results

About the only reasons for sticking to Timer I can think of are:

  • It is available pre Java 5
  • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

jQuery function after .append

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
  .append(html)
  .ready(function () {
    // enter code here
  });

How to show progress dialog in Android?

Point one you should remember when it comes to Progress dialog is that you should run it in a separate thread. If you run it in your UI thread you'll see no dialog.

If you are new to Android Threading then you should learn about AsyncTask. Which helps you to implement a painless Threads.

sample code

private class CheckTypesTask extends AsyncTask<Void, Void, Void>{
        ProgressDialog asyncDialog = new ProgressDialog(IncidentFormActivity.this);
        String typeStatus;


        @Override
        protected void onPreExecute() {
            //set message of the dialog
            asyncDialog.setMessage(getString(R.string.loadingtype));
            //show dialog
            asyncDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            //don't touch dialog here it'll break the application
            //do some lengthy stuff like calling login webservice

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //hide the dialog
            asyncDialog.dismiss();

            super.onPostExecute(result);
        }

}

Good luck.

Looping through list items with jquery

You need to use .each:

var listItems = $("#productList li");
listItems.each(function(idx, li) {
    var product = $(li);

    // and the rest of your code
});

This is the correct way to loop through a jQuery selection.


In modern Javascript you can also use a for .. of loop:

var listItems = $("#productList li");
for (let li of listItems) {
    let product = $(li);
}

Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.

SQL update query using joins

You can update with MERGE Command with much more control over MATCHED and NOT MATCHED:(I slightly changed the source code to demonstrate my point)

USE tempdb;
GO
IF(OBJECT_ID('target') > 0)DROP TABLE dbo.target
IF(OBJECT_ID('source') > 0)DROP TABLE dbo.source
CREATE TABLE dbo.Target
    (
      EmployeeID INT ,
      EmployeeName VARCHAR(100) ,
      CONSTRAINT Target_PK PRIMARY KEY ( EmployeeID )
    );
CREATE TABLE dbo.Source
    (
      EmployeeID INT ,
      EmployeeName VARCHAR(100) ,
      CONSTRAINT Source_PK PRIMARY KEY ( EmployeeID )
    );
GO
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 100, 'Mary' );
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 101, 'Sara' );
INSERT  dbo.Target
        ( EmployeeID, EmployeeName )
VALUES  ( 102, 'Stefano' );

GO
INSERT  dbo.Source
        ( EmployeeID, EmployeeName )
VALUES  ( 100, 'Bob' );
INSERT  dbo.Source
        ( EmployeeID, EmployeeName )
VALUES  ( 104, 'Steve' );
GO

SELECT * FROM dbo.Source
SELECT * FROM dbo.Target

MERGE Target AS T
USING Source AS S
ON ( T.EmployeeID = S.EmployeeID )
WHEN MATCHED THEN
    UPDATE SET T.EmployeeName = S.EmployeeName + '[Updated]';
GO 
SELECT '-------After Merge----------'
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target

An established connection was aborted by the software in your host machine

On a Windows box, I wanted to avoid reboot and these did not work: * /android/adt-bundle-windows/sdk/platform-tools/adb kill-server * /android/adt-bundle-windows/sdk/platform-tools/adb start-server

So what did work to get adb running again without this error was

  1. wait for the TIME WAIT to complete, which took multiple minutes. You can view the state of the ports and watch when to restart the debugger with this command: "PortQryV2/PortQry.exe -local" This tools is downloaded here: http://support.microsoft.com/?id=832919

  2. force closing ports with "netsh int tcp reset"

Configuring Hibernate logging using Log4j XML config file?

The answers were useful. After the change, I got duplicate logging of SQL statements, one in the log4j log file and one on the standard console. I changed the persistence.xml file to say show_sql to false to get rid of logging from the standard console. Keeping format_sql true also affects the log4j log file, so I kept that true.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:d:\temp\database\cap1000;shutdown=true"></property>
            <property name="dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        </properties>
    </persistence-unit>
</persistence>

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Where is database .bak file saved from SQL Server Management Studio?

Should be in

Program Files>Microsoft SQL Server>MSSQL 1.0>MSSQL>BACKUP>

In my case it is

C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup

If you use the gui or T-SQL you can specify where you want it T-SQL example

BACKUP DATABASE [YourDB] TO  DISK = N'SomePath\YourDB.bak' 
WITH NOFORMAT, NOINIT,  NAME = N'YourDB Full Database Backup', 
SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

With T-SQL you can also get the location of the backup, see here Getting the physical device name and backup time for a SQL Server database

SELECT          physical_device_name,
                backup_start_date,
                backup_finish_date,
                backup_size/1024.0 AS BackupSizeKB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
WHERE database_name = 'YourDB'
ORDER BY backup_finish_date DESC

Passing references to pointers in C++

EDIT: I experimented some, and discovered thing are a bit subtler than I thought. Here's what I now think is an accurate answer.

&s is not an lvalue so you cannot create a reference to it unless the type of the reference is reference to const. So for example, you cannot do

string * &r = &s;

but you can do

string * const &r = &s;

If you put a similar declaration in the function header, it will work.

void myfunc(string * const &a) { ... }

There is another issue, namely, temporaries. The rule is that you can get a reference to a temporary only if it is const. So in this case one might argue that &s is a temporary, and so must be declared const in the function prototype. From a practical point of view it makes no difference in this case. (It's either an rvalue or a temporary. Either way, the same rule applies.) However, strictly speaking, I think it is not a temporary but an rvalue. I wonder if there is a way to distinguish between the two. (Perhaps it is simply defined that all temporaries are rvalues, and all non-lvalues are temporaries. I'm not an expert on the standard.)

That being said, your problem is probably at a higher level. Why do you want a reference to the address of s? If you want a reference to a pointer to s, you need to define a pointer as in

string *p = &s;
myfunc(p);

If you want a reference to s or a pointer to s, do the straightforward thing.

Styling mat-select in Angular Material

Working solution is by using in-build: panelClass attribute and set styles in global style.css (with !important):

https://material.angular.io/components/select/api

_x000D_
_x000D_
/* style.css */
.matRole .mat-option-text {
  height: 4em !important;
}
_x000D_
<mat-select panelClass="matRole">...
_x000D_
_x000D_
_x000D_

How do I properly set the permgen size?

Completely removed from java 8 +
Partially removed from java 7 (interned Strings for example)
source

How to use filesaver.js

It works in my react project:

import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "hello world.txt");
}

Update multiple rows in same query using PostgreSQL

I don't think the accepted answer is entirely correct. It is order dependent. Here is an example that will not work correctly with an approach from the answer.

create table xxx (
    id varchar(64),
    is_enabled boolean
);

insert into xxx (id, is_enabled) values ('1',true);
insert into xxx (id, is_enabled) values ('2',true);
insert into xxx (id, is_enabled) values ('3',true);

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            VALUES
         (
            '3',
            false
         ,
            '1',
            true
         ,
            '2',
            false
         )
        ) AS u(id, is_enabled)
            WHERE u.id = pns.id;

select * from xxx;

So the question still stands, is there a way to do it in an order independent way?

---- after trying a few things this seems to be order independent

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            SELECT '3' as id, false as is_enabled UNION
            SELECT '1' as id, true as is_enabled UNION
            SELECT '2' as id, false as is_enabled
         ) as u
            WHERE u.id = pns.id;

Aggregate function in SQL WHERE-Clause

You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.

You can use a sub-query which contains an aggregate in the WHERE clause.

Capturing browser logs with Selenium WebDriver using Java

Adding LoggingPreferences to "goog:loggingPrefs" properties with the Chrome Driver options can help to fetch the Browser console logs for all Log levels.

ChromeOptions options = new ChromeOptions();    
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
options.setCapability("goog:loggingPrefs", logPrefs);
WebDriver driver = new ChromeDriver(options);

How can I list ALL DNS records?

There is no easy way to get all DNS records for a domain in one instance. You can only view certain records for example, if you wanna see an A record for a certain domain you can use the command: dig a(type of record) domain.com. This is the same for all the other type of records you wanna see for that domain.

If your not familiar with the command line interface, you can also use a site like mxtoolbox.com. Wich is very handy tool for getting records of a domain.

I hope this answers your question.

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

Is there a combination of "LIKE" and "IN" in SQL?

I was also wondering for something like that. I just tested using a combination of SUBSTRING and IN and it is an effective solution for this kind of problem. Try the below query :

Select * from TB_YOUR T1 Where SUBSTRING(T1.Something, 1,3) IN ('bla', 'foo', 'batz')

What does the ELIFECYCLE Node.js error mean?

One might think this is because outdated versions of npm and node, but it's not the case.

Just as Pierre Inglebert says, if you look into the source you can see that End of lifecycle means the program unexpectedly stopped. This can have various reasons. So it's not a syntax error and not an expected exception/error.

The error appeared to me when a different tool was already using the http port (3000) defined in my node scripts. When you run your node app on port 80, make sure you have stopped Apache webserver (as an example).

How can I compile and run c# program without using visual studio?

If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\

(Please do not edit, leave as a single line)

... The line above broken up for readability

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\

Javascript format date / time

Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:


Demo

I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.

moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm

How to delete shared preferences data from App in Android

You can always do it programmatically as suggested by the other answers over here. But for development purpose, I find this Plugin very helpful as it speeds up my development significantly.

PLUGIN: ADB Idea

It provides you with features to Clear App Data and Revoke Permission from your Android Studio itself, just with click of a button.

enter image description here

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

Get current working directory in a Qt application

To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;

// get the applications dir path and expose it to QML 

QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);


// Get the QStandardPaths home location and expose it to QML 
QUrl userPath;
   const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
   if (usersLocation.isEmpty())
       userPath = appPath.resolved(QUrl("/home/"));
   else
      userPath = QString("%1").arg(usersLocation.first());
   engine.rootContext()->setContextProperty("userPath", userPath);

   QUrl imagePath;
      const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
      if (picturesLocation.isEmpty())
          imagePath = appPath.resolved(QUrl("images"));
      else
          imagePath = QString("%1").arg(picturesLocation.first());
      engine.rootContext()->setContextProperty("imagePath", imagePath);

      QUrl videoPath;
      const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
      if (moviesLocation.isEmpty())
          videoPath = appPath.resolved(QUrl("./"));
      else
          videoPath = QString("%1").arg(moviesLocation.first());
      engine.rootContext()->setContextProperty("videoPath", videoPath);

      QUrl homePath;
      const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
      if (homesLocation.isEmpty())
          homePath = appPath.resolved(QUrl("/"));
      else
          homePath = QString("%1").arg(homesLocation.first());
      engine.rootContext()->setContextProperty("homePath", homePath);

      QUrl desktopPath;
      const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
      if (desktopsLocation.isEmpty())
          desktopPath = appPath.resolved(QUrl("/"));
      else
          desktopPath = QString("%1").arg(desktopsLocation.first());
      engine.rootContext()->setContextProperty("desktopPath", desktopPath);

      QUrl docPath;
      const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
      if (docsLocation.isEmpty())
          docPath = appPath.resolved(QUrl("/"));
      else
          docPath = QString("%1").arg(docsLocation.first());
      engine.rootContext()->setContextProperty("docPath", docPath);


      QUrl tempPath;
      const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
      if (tempsLocation.isEmpty())
          tempPath = appPath.resolved(QUrl("/"));
      else
          tempPath = QString("%1").arg(tempsLocation.first());
      engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}

Using it in QML

....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}

Difference between "on-heap" and "off-heap"

from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff

What is Heap-Offloading ?

Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.

However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.

One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).

So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.

The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.

It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).

Sample usage scenarios:

  • Session cache in a server application. Use a memory mapped file to store gigabytes of (inactive) user sessions. Once the user logs into your application, you can quickly access user-related data without having to deal with a database.
  • Caching of computational results (queries, html pages, ..) (only applicable if computation is slower than deserializing the result object ofc).
  • very simple and fast persistance using memory mapped files

Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.

bash: shortest way to get n-th column of output

If you are ok with manually selecting the column, you could be very fast using pick:

svn st | pick | xargs rm

Just go to any cell of the 2nd column, press c and then hit enter

How to call a stored procedure (with parameters) from another stored procedure without temp table

 Create PROCEDURE  Stored_Procedure_Name_2
  (
  @param1 int = 5  ,
  @param2 varchar(max),
  @param3 varchar(max)

 )
AS


DECLARE @Table TABLE
(
   /*TABLE DEFINITION*/
   id int,
   name varchar(max),
   address varchar(max)
)

INSERT INTO @Table 
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3

SELECT id ,name ,address  FROM @Table  

Reset auto increment counter in postgres

To reset the auto increment you have to get your sequence name by using following query.

Syntax:

SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);

Example:

SELECT pg_get_serial_sequence('demo', 'autoid');

The query will return the sequence name of autoid as "Demo_autoid_seq" Then use the following query to reset the autoid

Syntax:

ALTER SEQUENCE sequenceName RESTART WITH value;

Example:

ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;

Return value in a Bash function

$(...) captures the text sent to stdout by the command contained within. return does not output to stdout. $? contains the result code of the last command.

fun1 (){
  return 34
}

fun2 (){
  fun1
  local res=$?
  echo $res
}

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

What is the difference between & vs @ and = in angularJS

AngularJS – Isolated Scopes – @ vs = vs &


Short examples with explanation are available at below link :

http://www.codeforeach.com/angularjs/angularjs-isolated-scopes-vs-vs

@ – one way binding

In directive:

scope : { nameValue : "@name" }

In view:

<my-widget name="{{nameFromParentScope}}"></my-widget>

= – two way binding

In directive:

scope : { nameValue : "=name" },
link : function(scope) {
  scope.name = "Changing the value here will get reflected in parent scope value";
}

In view:

<my-widget name="{{nameFromParentScope}}"></my-widget>

& – Function call

In directive :

scope : { nameChange : "&" }
link : function(scope) {
  scope.nameChange({newName:"NameFromIsolaltedScope"});
}

In view:

<my-widget nameChange="onNameChange(newName)"></my-widget>