Programs & Examples On #Freebsd

FreeBSD is an advanced Unix-like operating system for modern server, desktop, and embedded computer platforms. It is open source and licensed under the 2-clause BSD license.

Determine the process pid listening on a certain port

Since sockstat wasn't natively installed on my machine I hacked up stanwise's answer to use netstat instead..

netstat -nlp | grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:2000" | awk '{print $7}' | sed -e "s/\/.*//g""

Check if string is neither empty nor space in shell script

Another quick test for a string to have something in it but space.

if [[ -n "${str// /}" ]]; then
    echo "It is not empty!"
fi

"-n" means non-zero length string.

Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.

You can read more about string manipulation in bash shell scripting here.

How can I get the behavior of GNU's readlink -f on a Mac?

FreeBSD and OSX have a version of statderived from NetBSD.

You can adjust the output with format switches (see the manual pages at the links above).

%  cd  /service
%  ls -tal 
drwxr-xr-x 22 root wheel 27 Aug 25 10:41 ..
drwx------  3 root wheel  8 Jun 30 13:59 .s6-svscan
drwxr-xr-x  3 root wheel  5 Jun 30 13:34 .
lrwxr-xr-x  1 root wheel 30 Dec 13 2013 clockspeed-adjust -> /var/service/clockspeed-adjust
lrwxr-xr-x  1 root wheel 29 Dec 13 2013 clockspeed-speed -> /var/service/clockspeed-speed
% stat -f%R  clockspeed-adjust
/var/service/clockspeed-adjust
% stat -f%Y  clockspeed-adjust
/var/service/clockspeed-adjust

Some OS X versions of stat may lack the -f%R option for formats. In this case -stat -f%Y may suffice. The -f%Y option will show the target of a symlink, whereas -f%R shows the absolute pathname corresponding to the file.

EDIT:

If you're able to use Perl (Darwin/OS X comes installed with recent verions of perl) then:

perl -MCwd=abs_path -le 'print abs_path readlink(shift);' linkedfile.txt

will work.

How to install packages offline?

offline python. for doing this I use virtualenv (isolated Python environment)

1) install virtualenv online with pip:

pip install virtualenv --user

or offline with whl: go to this link , download last version (.whl or tar.gz) and install that with this command:

pip install virtualenv-15.1.0-py2.py3-none-any.whl --user

by using --user you don't need to use sudo pip….

2) use virtualenv

on online machine select a directory with terminal cd and run this code:

python -m virtualenv myenv
cd myenv
source bin/activate
pip install Flask

after installing all the packages, you have to generate a requirements.txt so while your virtualenv is active, write

pip freeze > requirements.txt

open a new terminal and create another env like myenv2.

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
ls

now you can go to your offline folder where your requirements.txt and tranferred_packages folder are in there. download the packages with following code and put all of them to tranferred_packages folder.

pip download -r requirements.txt

take your offline folder to offline computer and then

python -m virtualenv myenv2
cd myenv2
source bin/activate
cd -
cd offline
pip install --no-index --find-links="./tranferred_packages" -r requirements.txt

what is in the folder offline [requirements.txt , tranferred_packages {Flask-0.10.1.tar.gz, ...}]

check list of your package

pip list

note: as we are in 2017 it is better to use python 3. you can create python 3 virtualenv with this command.

virtualenv -p python3 envname

How to provide shadow to Button

You can try this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<layer-list>
        <item android:left="1dp" android:top="3dp">
            <shape>
                <solid android:color="#a5040d" />
                <corners android:radius="3dip"/>
            </shape>
        </item>
    </layer-list>
  </item>
<item>
    <layer-list>
        <item android:left="0dp" android:top="0dp">
            <shape>
                    <solid android:color="#99080d" />
                <corners android:radius="3dip"/>
            </shape>
        </item>
        <item android:bottom="3dp" android:right="2dp">
            <shape>
                <solid android:color="#a5040d" />
                <corners android:radius="3dip"/>
            </shape>
        </item>
    </layer-list>
</item>

How to update column with null value

if you set NULL for all records try this:

UPDATE `table_name` SET `column_you_want_set_null`= NULL

OR just set NULL for special records use WHERE

UPDATE `table_name` SET `column_you_want_set_null`= NULL WHERE `column_name` = 'column_value' 

Invalid hook call. Hooks can only be called inside of the body of a function component

complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

No server in windows>preferences

You did not install the correct Eclipse distribution. Try install the one labeled "Eclipse IDE for Java EE Developers".

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

How can I change the date format in Java?

tl;dr

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

2017/01/23

Avoid legacy date-time classes

The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

Using java.time

Parse the input string as a date-time object, then generate a new String object in the desired format.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

Define another formatter for the output.

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

By the way, consider using standard ISO 8601 formats for strings representing date-time values.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.

For fun, here is his code adapted for using the Joda-Time library.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );

Dump to console…

System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );

When run…

localDate: 2010-08-12
newDateString: 2010/08/12

Unicode characters in URLs

Use percent encoding. Modern browsers will take care of display & paste issues and make it human-readable. E. g. http://ko.wikipedia.org/wiki/????:??

Edit: when you copy such an url in Firefox, the clipboard will hold the percent-encoded form (which is usually a good thing), but if you copy only a part of it, it will remain unencoded.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Getting "type or namespace name could not be found" but everything seems ok?

In my case, adding the dll as a reference gave the type or namespace name could not be found error. However, copying and pasting the dll file directly in bin folder resolved the error.

No idea why this worked.

Github Windows 'Failed to sync this branch'

I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status command Git Shell suggested to push changes as

Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

I did the same as Git Shell suggested (git push) and everything is ok now.

Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.

fatal: Not a git repository (or any of the parent directories):

For example if your Project is in D drive in some folder you have to do something like below as you do in cmd to change directory.

cd D:\someFolder     // if your project is not deep in `D`

And if its within nested folder in D

cd D:\somefolder\someNestedFolder\nestedInNested     // if your project is not deep in `D`

If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

How do I analyze a .hprof file?

You can use JHAT, The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. A very useful view is the "heap histogram" link at the very bottom.

ex: jhat -port 7401 -J-Xmx4G dump.hprof

jhat can execute OQL "these days" as well (bottom link "execute OQL")

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Message Queue vs. Web Services?

There's been a fair amount of recent research in considering how REST HTTP calls could replace the message queue concept.

If you introduce the concept of a process and a task as a resource, the need for middle messaging layer starts to evaporate.

Ex:

POST /task/name
    - Returns a 202 accepted status immediately
    - Returns a resource url for the created task: /task/name/X
    - Returns a resource url for the started process: /process/Y

GET /process/Y
    - Returns status of ongoing process

A task can have multiple steps for initialization, and a process can return status when polled or POST to a callback URL when complete.

This is dead simple, and becomes quite powerful when you realize that you can now subscribe to an rss/atom feed of all running processes and tasks without any middle layer. Any queuing system is going to require some sort of web front end anyway, and this concept has it built in without another layer of custom code.

Your resources exist until you delete them, which means you can view historical information long after the process and task complete.

You have built in service discovery, even for a task that has multiple steps, without any extra complicated protocols.

GET /task/name
    - returns form with required fields

POST (URL provided form's "action" attribute)

Your service discovery is an HTML form - a universal and human readable format.

The entire flow can be used programmatically or by a human, using universally accepted tools. It's a client driven, and therefore RESTful. Every tool created for the web can drive your business processes. You still have alternate message channels by POSTing asynchronously to a separate array of log servers.

After you consider it for a while, you sit back and start to realize that REST may just eliminate the need for a messaging queue and an ESB altogether.

http://www.infoq.com/presentations/BPM-with-REST

Get real path from URI, Android KitKat new storage access framework

Before new gallery access in KitKat I got my real path in sdcard with this method

That was never reliable. There is no requirement that the Uri that you are returned from an ACTION_GET_CONTENT or ACTION_PICK request has to be indexed by the MediaStore, or even has to represent a file on the file system. The Uri could, for example, represent a stream, where an encrypted file is decrypted for you on the fly.

How could I manage to obtain the real path in sdcard?

There is no requirement that there is a file corresponding to the Uri.

Yes, I really need a path

Then copy the file from the stream to your own temporary file, and use it. Better yet, just use the stream directly, and avoid the temporary file.

I have changed my Intent.ACTION_GET_CONTENT for Intent.ACTION_PICK

That will not help your situation. There is no requirement that an ACTION_PICK response be for a Uri that has a file on the filesystem that you can somehow magically derive.

C# Switch-case string starting with

If you knew that the length of conditions you would care about would all be the same length then you could:

switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
  case "abc":
    //do something
    break;
  case "xyz":
    //do something else
    break;
  default:
    //do a different thing
    break;
}

The Math.Min(3, mystring.Length) is there so that a string of less than 3 characters won't throw an exception on the sub-string operation.

There are extensions of this technique to match e.g. a bunch of 2-char strings and a bunch of 3-char strings, where some 2-char comparisons matching are then followed by 3-char comparisons. Unless you've a very large number of such strings though, it quickly becomes less efficient than simple if-else chaining for both the running code and the person who has to maintain it.

Edit: Added since you've now stated they will be of different lengths. You could do the pattern I mentioned of checking the first X chars and then the next Y chars and so on, but unless there's a pattern where most of the strings are the same length this will be both inefficient and horrible to maintain (a classic case of premature pessimisation).

The command pattern is mentioned in another answer, so I won't give details of that, as is that where you map string patterns to IDs, but they are option.

I would not change from if-else chains to command or mapping patterns to gain the efficiency switch sometimes has over if-else, as you lose more in the comparisons for the command or obtaining the ID pattern. I would though do so if it made code clearer.

A chain of if-else's can work pretty well, either with string comparisons or with regular expressions (the latter if you have comparisons more complicated than the prefix-matches so far, which would probably be simpler and faster, I'm mentioning reg-ex's just because they do sometimes work well with more general cases of this sort of pattern).

If you go for if-elses, try to consider which cases are going to happen most often, and make those tests happen before those for less-common cases (though of course if "starts with abcd" is a case to look for it would have to be checked before "starts with abc").

Factory Pattern. When to use factory methods?

It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods are lighter weight (and also tend to be testable, since they don't have a defined type, but they will require a well-known registration point, akin to a service locator but for locating factory methods).

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

You have to load jdbc driver. Consider below Code.

try {
           Class.forName("com.mysql.jdbc.Driver");

            // connect way #1
            String url1 = "jdbc:mysql://localhost:3306/aavikme";
            String user = "root";
            String password = "aa";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {
                System.out.println("Connected to the database test1");
            }

            // connect way #2
            String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            // connect way #3
            String url3 = "jdbc:mysql://localhost:3306/aavikme";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "aa");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
   } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

How to close a window using jQuery

$(element).click(function(){
    window.close();
});

Note: you can not close any window that you didn't opened with window.open. Directly invoking window.close() will ask user with a dialogue box.

How to make the script wait/sleep in a simple way in unity

here is more simple way without StartCoroutine:

float t = 0f;
float waittime = 1f;

and inside Update/FixedUpdate:

if (t < 0){
    t += Time.deltaTIme / waittime;
    yield return t;
}

Insert multiple rows with one query MySQL

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";


 if ($conn->multi_query($sql) === TRUE) {

  echo "New records created successfully";

 } else {

   echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

Source W3schools

What is the difference between a URI, a URL and a URN?

URL

A URL is a specialization of URI that defines the network location of a specific resource. Unlike a URN, the URL defines how the resource can be obtained. We use URLs every day in the form of http://example.com etc. But a URL doesn't have to be an HTTP URL, it can be ftp://example.com etc., too.

URI

A URI identifies a resource either by location, or a name, or both. More often than not, most of us use URIs that defines a location to a resource. The fact that a URI can identify a resources by both name and location has lead to a lot of the confusion in my opinion. A URI has two specializations known as URL and URN.

Difference between URL and URI

A URI is an identifier for some resource, but a URL gives you specific information as to obtain that resource. A URI is a URL and as one commenter pointed out, it is now considered incorrect to use URL when describing applications. Generally, if the URL describes both the location and name of a resource, the term to use is URI. Since this is generally the case most of us encounter everyday, URI is the correct term.

Is there a way to avoid null check before the for-each loop iteration starts?

I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null

How do you change the width and height of Twitter Bootstrap's tooltips?

Define the max-width with "important!" and use data-container="body"

CSS file

.tooltip-inner {
    max-width: 500px !important;
}

HTML tag

<a data-container="body" title="Looooooooooooooooooooooooooooooooooooooong Message" href="#" class="tooltiplink" data-toggle="tooltip" data-placement="bottom" data-html="true"><i class="glyphicon glyphicon-info-sign"></i></a>

JS script

$('.tooltiplink').tooltip();

How to convert a string to lower case in Bash?

Converting case is done for alphabets only. So, this should work neatly.

I am focusing on converting alphabets between a-z from upper case to lower case. Any other characters should just be printed in stdout as it is...

Converts the all text in path/to/file/filename within a-z range to A-Z

For converting lower case to upper case

cat path/to/file/filename | tr 'a-z' 'A-Z'

For converting from upper case to lower case

cat path/to/file/filename | tr 'A-Z' 'a-z'

For example,

filename:

my name is xyz

gets converted to:

MY NAME IS XYZ

Example 2:

echo "my name is 123 karthik" | tr 'a-z' 'A-Z'
# Output:
# MY NAME IS 123 KARTHIK

Example 3:

echo "my name is 123 &&^&& #@$#@%%& kAR2~thik" | tr 'a-z' 'A-Z'
# Output:
# MY NAME IS 123 &&^&& #@0@%%& KAR2~THIK

Javascript : natural sort of alphanumerical strings

This is now possible in modern browsers using localeCompare. By passing the numeric: true option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'. Tested in Chrome, Firefox, and IE11.

Here's an example. It returns 1, meaning 10 goes after 2:

'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})

For performance when sorting large numbers of strings, the article says:

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link

_x000D_
_x000D_
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});_x000D_
var myArray = ['1_Document', '11_Document', '2_Document'];_x000D_
console.log(myArray.sort(collator.compare));
_x000D_
_x000D_
_x000D_

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

How to change the icon of .bat file programmatically?

If you want an icon for a batch file, first create a link for the batch file as follows

Right click in window folder where you want the link select New -> Shortcut, then specify where the .bat file is.

This creates the .lnk file you wanted. Then you can specify an icon for the link, on its properties page.

Some nice icons are available here:

%SystemRoot%\System32\SHELL32.dll

Note For me on Windows 10: %SystemRoot% == C:\Windows\

More Icons are here: C:\Windows\System32\imageres.dll

Also you might want to have the first line in the batch file to be "cd .." if you stash your batch files in a bat subdirectory one level below where your shortcuts, are supposed to execute.

Use and meaning of "in" in an if statement?

You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!

How to add 30 minutes to a JavaScript Date object?

it is simple as it is;

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));

GitHub "fatal: remote origin already exists"

The concept of remote is simply the URL of your remote repository.

The origin is an alias pointing to that URL. So instead of writing the whole URL every single time we want to push something to our repository, we just use this alias and run:

git push -u origin master

Telling to git to push our code from our local master branch to the remote origin repository.

Whenever we clone a repository, git creates this alias for us by default. Also whenever we create a new repository, we just create it our self.

Whatever the case it is, we can always change this name to anything we like, running this:

git remote rename [current-name] [new-name]

Since it is stored on the client side of the git application (on our machine) changing it will not affect anything in our development process, neither at our remote repository. Remember, it is only a name pointing to an address.

The only thing that changes here by renaming the alias, is that we have to declare this new name every time we push something to our repository.

git push -u my-remote-alias master

Obviously a single name can not point to two different addresses. That's why you get this error message. There is already an alias named origin at your local machine. To see how many aliases you have and what are they, you can initiate this command:

git remote -v

This will show you all the aliases you have plus the corresponding URLs.

You can remove them as well if you like running this:

git remote rm my-remote-alias

So in brief:

  • find out what do you have already,
  • remove or rename them,
  • add your new aliases.

Happy coding.

How to position a div in the middle of the screen when the page is bigger than the screen

position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;

This worked for me

How to store arbitrary data for some HTML tags

Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).

<a class="article" href="link/for/non-js-users.html">
    <span style="display: none;">{"id": 1, "title":"Something"}</span>
    Text of Link
</a>

// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);

Difference between Eclipse Europa, Helios, Galileo

Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).

A process crashed in windows .. Crash dump location

Windows 7, 64 bit, no modifications to the Registry key, the location is:

C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive

Serializing an object as UTF-8 XML in .NET

Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).

To get the actual UTF-8 octets you could use:

var serializer = new XmlSerializer(typeof(SomeSerializableObject));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);

serializer.Serialize(streamWriter, entry);

byte[] utf8EncodedXml = memoryStream.ToArray();

I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):

var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var  xw = XmlWriter.Create(memStm))
{
  serializer.Serialize(xw, entry);
  var utf8 = memStm.ToArray();
}

Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.

C#: how to get first char of a string?

The difference between MyString[0] and MyString.ToCharArray()[0] is that the former treats the string as a read-only array, while ToCharArray() creates a new array. The former will be quicker (along with easier) for almost anything where it will work, but ToCharArray can be necessary if you have a method that needs to accept an array, or if you want to change the array.

If the string isn't known to be non-null and non-empty you could do:

string.IsNullOrEmpty(MyString) ? (char?)null : MyString[0]

which returns a char? of either null or the first character in the string, as appropriate.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.

What's the difference between all the Selection Segues?

For clarity, I'd like to illustrate @Joey's answer above with these gifs :

Show

enter image description here

Show Detail

enter image description here

Present Modally

enter image description here

Present As Popover

enter image description here

Speed up rsync with Simultaneous/Concurrent File Transfers?

You can use xargs which supports running many processes at a time. For your case it will be:

ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/

Return content with IHttpActionResult for non-OK response

A more detailed example with support of HTTP code not defined in C# HttpStatusCode.

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        HttpStatusCode codeNotDefined = (HttpStatusCode)429;
        return Content(codeNotDefined, "message to be sent in response body");
    }
}

Content is a virtual method defined in abstract class ApiController, the base of the controller. See the declaration as below:

protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

What does body-parser do with express?

Understanding Requests Body

When receiving a POST or PUT request, the request body might be important to your application. Getting at the body data is a little more involved than accessing request headers. The request object that's passed in to a handler implements the ReadableStream interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.

The chunk emitted in each 'data' event is a Buffer. If you know it's going to be string data, the best thing to do is collect the data in an array, then at the 'end', concatenate and stringify it.

let body = [];
request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

Understanding body-parser

As per its documentation

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

As you saw in the first example, we had to parse the incoming request stream manually to extract the body. This becomes a tad tedious when there are multiple form data of different types. So we use the body-parser package which does all this task under the hood.

It provides four modules to parse different types of data

After having the raw content body-parser will use one of the above strategies(depending on middleware you decided to use) to parse the data. You can read more about them by reading their documentation.

After setting the req.body to the parsed body, body-parser will invoke next() to call the next middleware down the stack, which can then access the request data without having to think about how to unzip and parse it.

How to force an entire layout View refresh?

To clear a view extending ViewGroup, you just need to use the method removeAllViews()

Just like this (if you have a ViewGroup called myElement) :

myElement.removeAllViews()

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Add a fragment to the URL without causing a redirect?

window.location.hash = 'whatever';

What does "hashable" mean in Python?

For creating a hashing table from scratch, all the values has to set to "None" and modified once a requirement arises. Hashable objects refers to the modifiable datatypes(Dictionary,lists etc). Sets on the other hand cannot be reinitialized once assigned, so sets are non hashable. Whereas, The variant of set() -- frozenset() -- is hashable.

Measuring text height to be drawn on Canvas ( Android )

You can simply get the text size for a Paint object using getTextSize() method. For example:

Paint mTextPaint = new Paint (Paint.ANTI_ALIAS_FLAG);
//use densityMultiplier to take into account different pixel densities
final float densityMultiplier = getContext().getResources()
            .getDisplayMetrics().density;  
mTextPaint.setTextSize(24.0f*densityMultiplier);

//...

float size = mTextPaint.getTextSize();

Java for loop multiple variables

Instead of this : for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){

It should be

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
                                     ^         ^    ^  
                                     |         |    |  
                                     |         |    |  
            -------------------------------------------Note the changes
           |                    
           v                                                  |
   if(rank==cards.substring(a,b){                             |
-------------------------------------------------------------                                  
|
v
System.out.println(c); //capital S in system

Why is setState in reactjs Async instead of Sync?

Imagine incrementing a counter in some component:

  class SomeComponent extends Component{

    state = {
      updatedByDiv: '',
      updatedByBtn: '',
      counter: 0
    }

    divCountHandler = () => {
      this.setState({
        updatedByDiv: 'Div',
        counter: this.state.counter + 1
      });
      console.log('divCountHandler executed');
    }

    btnCountHandler = () => {
      this.setState({
        updatedByBtn: 'Button',
        counter: this.state.counter + 1
      });
      console.log('btnCountHandler executed');
    }
    ...
    ...
    render(){
      return (
        ...
        // a parent div
        <div onClick={this.divCountHandler}>
          // a child button
          <button onClick={this.btnCountHandler}>Increment Count</button>
        </div>
        ...
      )
    }
  }

There is a count handler attached to both the parent and the child components. This is done purposely so we can execute the setState() twice within the same click event bubbling context, but from within 2 different handlers.

As we would imagine, a single click event on the button would now trigger both these handlers since the event bubbles from target to the outermost container during the bubbling phase.

Therefore the btnCountHandler() executes first, expected to increment the count to 1 and then the divCountHandler() executes, expected to increment the count to 2.

However the count only increments to 1 as you can inspect in React Developer tools.

This proves that react

  • queues all the setState calls

  • comes back to this queue after executing the last method in the context(the divCountHandler in this case)

  • merges all the object mutations happening within multiple setState calls in the same context(all method calls within a single event phase is same context for e.g.) into one single object mutation syntax (merging makes sense because this is why we can update the state properties independently in setState() in the first place)

  • and passes it into one single setState() to prevent re-rendering due to multiple setState() calls (this is a very primitive description of batching).

Resultant code run by react:

this.setState({
  updatedByDiv: 'Div',
  updatedByBtn: 'Button',
  counter: this.state.counter + 1
})

To stop this behaviour, instead of passing objects as arguments to the setState method, callbacks are passed.

    divCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByDiv: 'Div',
              counter: prevState.counter + 1
            };
          });
          console.log('divCountHandler executed');
        }

    btnCountHandler = () => {
          this.setState((prevState, props) => {
            return {
              updatedByBtn: 'Button',
              counter: prevState.counter + 1
            };
          });
      console.log('btnCountHandler executed');
    }

After the last method finishes execution and when react returns to process the setState queue, it simply calls the callback for each setState queued, passing in the previous component state.

This way react ensures that the last callback in the queue gets to update the state that all of its previous counterparts have laid hands on.

Get number of digits with JavaScript

Here is my solution. It works with positive and negative numbers. Hope this helps

function findDigitAmount(num) {

   var positiveNumber = Math.sign(num) * num;
   var lengthNumber = positiveNumber.toString();

 return lengthNumber.length;
}


(findDigitAmount(-96456431);    // 8
(findDigitAmount(1524):         // 4

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

check if variable empty

empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

Delete everything in a MongoDB database

I had the same problem, when I needed to reset all the collections but didn't want to loose any database users. Use the following line of code, if you would like to save the user configuration for the database:

use <whichever database>
db.getCollectionNames().forEach(function(c) { if (c.indexOf("system.") == -1) db[c].drop(); })

This code will go through all collection names from one database and drop those which do not start with "system.".

Array functions in jQuery

jQuery has very limited array functions since JavaScript has most of them itself. But here are the ones they have: Utilities - jQuery API.

Conditional formatting based on another cell's value

Note: when it says "B5" in the explanation below, it actually means "B{current_row}", so for C5 it's B5, for C6 it's B6 and so on. Unless you specify $B$5 - then you refer to one specific cell.


This is supported in Google Sheets as of 2015: https://support.google.com/drive/answer/78413#formulas

In your case, you will need to set conditional formatting on B5.

  • Use the "Custom formula is" option and set it to =B5>0.8*C5.
  • set the "Range" option to B5.
  • set the desired color

You can repeat this process to add more colors for the background or text or a color scale.

Even better, make a single rule apply to all rows by using ranges in "Range". Example assuming the first row is a header:

  • On B2 conditional formatting, set the "Custom formula is" to =B2>0.8*C2.
  • set the "Range" option to B2:B.
  • set the desired color

Will be like the previous example but works on all rows, not just row 5.

Ranges can also be used in the "Custom formula is" so you can color an entire row based on their column values.

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

Change window location Jquery

Assuming you want to change the url to another within the same domain, you can use this:

history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');

How to reload/refresh an element(image) in jQuery

Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.

function imageUploadComplete () {
    $("#image_container").html("<img src='" + newImageUrl + "'>");
}

How can I initialize an ArrayList with all zeroes in Java?

The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).

To initialize an list with 60 zeros you do:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));

If you want to create a list with 60 different objects, you could use the Stream API with a Supplier as follows:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.

Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

Remove everything after a certain character

It works for me very nicely:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);

How to Display Selected Item in Bootstrap Button Dropdown Title

you need to use add class open in <div class="btn-group open">

and in li add class="active"

How to execute python file in linux

Add this at the top of your file:

#!/usr/bin/python

This is a shebang. You can read more about it on Wikipedia.

After that, you must make the file executable via

chmod +x your_script.py

Google Maps shows "For development purposes only"

Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free. That is why you get the watermarked maps.

For more information, see: https://cloud.google.com/maps-platform/pricing/

Update: A common problem with the new billing system is that you now have to activate each API separately. They all have different pricing (some are even free), so Google makes a point of having you enable them individually for your domain. I was never a heavy user of Google Maps, but I get the feeling that there are many more APIs now than there used to be.

So if you're still getting a restricted usage message after you've enabled billing, find out what API you need exactly for the features you want to offer, and check if it's enabled. The API settings are annoyingly hard to find.

  1. Go to this link: https://console.developers.google.com/apis/dashboard.
  2. Then you select your project in the dropdown.
  3. Go to library on the left pane.
  4. Browse the available APIs and enable the one you need.

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.

When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).

It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.

So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.

Incomplete type is not allowed: stringstream

Some of the system headers provide a forward declaration of std::stringstream without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream> header:

#include <sstream>

How do I split a string, breaking at a particular character?

Use this code --

function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}

Gridview row editing - dynamic binding to a DropDownList

You can use SelectedValue:

<EditItemTemplate>
    <asp:DropDownList ID="ddlPBXTypeNS"
                      runat="server"
                      Width="200px"
                      DataSourceID="YDS"
                      DataTextField="CaptionValue"
                      DataValueField="OID"
                      SelectedValue='<%# Bind("YourForeignKey") %>' />
    <asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>

How to implement a queue using two stacks?

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.

pop() -- Removes the element from in front of queue.

peek() -- Get the front element.

empty() -- Return whether the queue is empty.

enter image description here

class MyQueue {

  Stack<Integer> input;
  Stack<Integer> output;

  /** Initialize your data structure here. */
  public MyQueue() {
    input = new Stack<Integer>();
    output = new Stack<Integer>();
  }

  /** Push element x to the back of queue. */
  public void push(int x) {
    input.push(x);
  }

  /** Removes the element from in front of queue and returns that element. */
  public int pop() {
    peek();
    return output.pop();
  }

  /** Get the front element. */
  public int peek() {
    if(output.isEmpty()) {
        while(!input.isEmpty()) {
            output.push(input.pop());
        }
    }
    return output.peek();
  }

  /** Returns whether the queue is empty. */
  public boolean empty() {
    return input.isEmpty() && output.isEmpty();
  }
}

How to use sed to remove the last n lines of a file

It can be done in 3 steps:

a) Count the number of lines in the file you want to edit:

 n=`cat myfile |wc -l`

b) Subtract from that number the number of lines to delete:

 x=$((n-3))

c) Tell sed to delete from that line number ($x) to the end:

 sed "$x,\$d" myfile

Why are hexadecimal numbers prefixed with 0x?

The preceding 0 is used to indicate a number in base 2, 8, or 16.

In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.

Just my opinion, but I think it makes sense.

Good Day!

How to debug Angular JavaScript Code

1. Chrome

For debugging AngularJS in Chrome you can use AngularJS Batarang. (From recent reviews on the plugin it seems like AngularJS Batarang is no longer being maintained. Tested in various versions of Chrome and it does not work.)

Here is the the link for a description and demo: Introduction of Angular JS Batarang

Download Chrome plugin from here: Chrome plugin for debugging AngularJS

You can also use ng-inspect for debugging angular.

2. Firefox

For Firefox with the help of Firebug you can debug the code.

Also use this Firefox Add-Ons: AngScope: Add-ons for Firefox (Not official extension by AngularJS Team)

3. Debugging AngularJS

Check the Link: Debugging AngularJS

Variable might not have been initialized error

If they were declared as fields of the class then they would be really initialized with 0.

You're a bit confused because if you write:

class Clazz {
  int a;
  int b;

  Clazz () {
     super ();
     b = 0;
  }

  public void printA () {
     sout (a + b);
  }

  public static void main (String[] args) {
     new Clazz ().printA ();
  }
}

Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

In my case, the error occured in phpmyadmin version 4.5.1 when i set lower_case_table_names = 2 and had a table name with uppercase characters, The table had a primary key set to auto increment but still showed the error. The issue stopped when i changed the table name to all lowercase.

(413) Request Entity Too Large | uploadReadAheadSize

For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

How to apply multiple transforms in CSS?

You can also apply multiple transforms using an extra layer of markup e.g.:

<h3 class="rotated-heading">
    <span class="scaled-up">Hey!</span>
</h3>
<style type="text/css">
.rotated-heading
{
    transform: rotate(10deg);
}

.scaled-up
{
    transform: scale(1.5);
}
</style>

This can be really useful when animating elements with transforms using Javascript.

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

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

You can use cut to access the second field:

cut -f2

Edit: Sorry, didn't realise that SVN doesn't use tabs in its output, so that's a bit useless. You can tailor cut to the output but it's a bit fragile - something like cut -c 10- would work, but the exact value will depend on your setup.

Another option is something like: sed 's/.\s\+//'

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality


The addwithvalue method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add method requires that you specify the Database type first. This helps to reduce such errors.

For more detail Please click here

ValidateAntiForgeryToken purpose, explanation and example

Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.

From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:

Use of ValidateAntiForgeryToken

Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.

  1. Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.

  2. Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.

`

<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF;
Integrated Security=true;" providerName="System.Data.SqlClient" /> 
 </connectionStrings>
  1. Now, click on Tools >> NuGet Package Manager, then Package Manager Console

  2. Now, run the below mentioned three commands in Package Manager Console to create the database.

Enable-Migrations add-migration first update-database

Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.

  1. Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:

http://localhost:52269/Account/Register

Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.

  1. Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.

    Registration Form
    1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
    2. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
    3. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)

7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.

8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.

  1. Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.

Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.

This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.

How to draw a checkmark / tick using CSS?

i like this way because you don't need to create two components just one.

.checkmark:after {
    opacity: 1;
    height: 4em;
    width: 2em;
    -webkit-transform-origin: left top;
    transform-origin: left top;
    border-right: 2px solid #5cb85c;
    border-top: 2px solid #5cb85c;
    content: '';
    left: 2em;
    top: 4em;
    position: absolute;
}

Animation from Scott Galloway Pen

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

Show DialogFragment with animation growing from a point

In DialogFragment, custom animation is called onCreateDialog. 'DialogAnimation' is custom animation style in previous answer.

public Dialog onCreateDialog(Bundle savedInstanceState) 
{
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
    return dialog;
}

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

JQuery: dynamic height() with window resize()

The cleanest solution - also purely CSS - would be using calc and vh.

The middle div's heigh will be calculated thusly:

#middle-div { 
height: calc(100vh - 46px); 
}

That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

Are there any style options for the HTML5 Date picker?

FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color, fill, etc.

I did eventually figure out that some filter properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:

_x000D_
_x000D_
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
  background: transparent;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
 <input type="date" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

Hopefully this helps some people as for the most part chrome even directly says this is impossible.

Add new element to an existing object

jQuery syntax mentioned above by Danilo Valente is not working. It should be as following-

$.extend(myFunction,{
    bookName:'mybook',
    bookdesc: 'new'
});

Didn't Java once have a Pair class?

If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set

public class Pair<First, Second> {
    private First first;
    private Second second;

    public Pair(First first, Second second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(First first) {
        this.first = first;
    }

    public void setSecond(Second second) {
        this.second = second;
    }

    public First getFirst() {
        return first;
    }

    public Second getSecond() {
        return second;
    }

    public void set(First first, Second second) {
        setFirst(first);
        setSecond(second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair pair = (Pair) o;

        if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
        if (second != null ? !second.equals(pair.second) : pair.second != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }
}

Why do I have ORA-00904 even when the column is present?

It could be a case-sensitivity issue. Normally tables and columns are not case sensitive, but they will be if you use quotation marks. For example:

create table bad_design("goodLuckSelectingThisColumn" number);

Finding diff between current and last version

I use Bitbucket with the Eclipse IDE with the Eclipse EGit plugin installed.

I compare a file from any version of its history (like SVN).

Menu Project Explorer → File → right click → TeamShow in history.

This will bring the history of all changes on that file. Now Ctrl click and select any two versions→ "Compare with each other".

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

Empty ArrayList equals null

No.

An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty. You can check for am empty ArrayList with:

ArrayList arrList = new ArrayList();
if(arrList.isEmpty())
{
    // Do something with the empty list here.
}

Or if you want to create a method that checks for an ArrayList with only nulls:

public static Boolean ContainsAllNulls(ArrayList arrList)
{
    if(arrList != null)
    {
        for(object a : arrList)
            if(a != null) return false;
    }

    return true;
}

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

How to delete the last row of data of a pandas dataframe

Since index positioning in Python is 0-based, there won't actually be an element in index at the location corresponding to len(DF). You need that to be last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

However, it's much simpler to just write DF[:-1].

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Excel is not updating cells, options > formula > workbook calculation set to automatic

I had a similar issue with a VLOOKUP. The field I was using to VLOOKUP was formatted as a custom field. Excel was saying it was a number stored as text. Clearing this error (selecting all fields with the error, beginning with the first one with the error and clicking change to Number even though I didn't really want it to be!) fixed it.

How can I pipe stderr, and not stdout?

This also works (and I find it a tiny bit easier to remember)

command 2> /dev/fd/1 | grep 'something'

More info about /dev/fd directory here

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

For future reference:

 yyyy => 4 digit year
 MM   => 2 digit month (you must type MM in ALL CAPS)
 dd   => 2 digit "day of the month"

 HH   => 2-digit "hour in day" (0 to 23)
 mm   => 2-digit minute (you must type mm in lowercase)
 ss   => 2-digit seconds
 SSS  => milliseconds

So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"

But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"

The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!

How do you check what version of SQL Server for a database using TSQL?

Here's a bit of script I use for testing if a server is 2005 or later

declare @isSqlServer2005 bit
select @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end
select @isSqlServer2005

Note : updated from original answer (see comment)

How to compare variables to undefined, if I don’t know whether they exist?

!undefined is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:

if(<object or variable>) {
     //take actions if object is not undefined
} else {
     //take actions if object is undefined
}

failed to find target with hash string 'android-22'

Open the Android SDK Manager and Update with latest :

  1. Android SDK Tools
  2. Android SDK Build Tools

Then Sync ,Re-Build and Restart Your Project Demo Code for build.gradle

   compileSdkVersion 21 // Now 23
   buildToolsVersion '21.1.2' //Now 23.0.1

   defaultConfig
    {
    minSdkVersion 15
    targetSdkVersion 19  
     }

Hope this helps .

Adding a newline character within a cell (CSV)

I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.

  $itemCode =  '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){

    if($checkkey >0){
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
    }else{
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";             
    }
    $repairDetaile[]= array(
        $itemCode,
    )
}
// pass all array to here 
foreach ($repairDetaile as $csvData) { 
    fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);  

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

What's the best way to calculate the size of a directory in .NET?

I try to change the sample (Alexandre Pepin and hao's Answer)

As is

    private long GetDirectorySize(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        FileInfo[] fis = dirInfo.GetFiles();
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        // Add subdirectory sizes.
        DirectoryInfo[] dis = dirInfo.GetDirectories();
        foreach (DirectoryInfo di in dis)
        {
            size += GetDirectorySize(di.FullName);
        }

        return size;
    }

To be

    private long GetDirectorySize2(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        IEnumerable<FileInfo> fis = dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        return size;
    }

finally you can check the result

        // ---------------------------------------------
        // size of directory
        using System.IO;

        string log1Path = @"D:\SampleDirPath1";
        string log2Path = @"D:\SampleDirPath2";
        string log1DirName = Path.GetDirectoryName(log1Path);
        string log2DirName = Path.GetDirectoryName(log2Path);
        long log1Size = GetDirectorySize(log1Path);
        long log2Size = GetDirectorySize(log2Path);
        long log1Size2 = GetDirectorySize2(log1Path);
        long log2Size2 = GetDirectorySize2(log2Path);

        Console.WriteLine($@"{log1DirName} Size: {SizeSuffix(log1Size)}, {SizeSuffix(log1Size2)}
        {log2DirName} Size: {SizeSuffix(log2Size)}, {SizeSuffix(log2Size2)}");

and this is the SizeSuffix function

    private static readonly string[] SizeSuffixes =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    /// <summary>
    /// Size Display
    /// </summary>
    /// <param name="value">bytes ??</param>
    /// <param name="decimalPlaces">????</param>
    /// <returns></returns>
    public static string SizeSuffix(Int64 value, int decimalPlaces = 2)
    {
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag) 
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
        {
            mag += 1;
            adjustedSize /= 1024;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}",
            adjustedSize,
            SizeSuffixes[mag]);
    }

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Is it possible to change javascript variable values while debugging in Google Chrome?

To modify a value every time a block of code runs without having to break execution flow:

The "Logpoints" feature in the debugger is designed to let you log arbitrary values to the console without breaking. It evaluates code inside the flow of execution, which means you can actually use it to change values on the fly without stopping.

Right-click a line number and choose "Logpoint," then enter the assignment expression. It looks something like this:

enter image description here

I find it super useful for setting values to a state not otherwise easy to reproduce, without having to rebuild my project with debug lines in it. REMEMBER to delete the breakpoint when you're done!

PostgreSQL: Why psql can't connect to server?

The error states that the psql utility can't find the socket to connect to your database server. Either you don't have the database service running in the background, or the socket is located elsewhere, or perhaps the pg_hba.conf needs to be fixed.

Step 1: Verify that the database is running

The command may vary depending on your operating system. But on most *ix systems the following would work, it will search for postgres among all running processes

ps -ef | grep postgres

On my system, mac osx, this spits out

501   408     1   0  2Jul15 ??         0:21.63 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres -r /usr/local/var/postgres/server.log

The last column shows the command used to start the server, and the options.

You can look at all the options available to start the postgres server using the following.

man postgres

From there, you'd see that the options -D and -r are respectively the datadir & the logfilename.

Step 2: If the postgres service is running

Use find to search for the location of the socket, which should be somewhere in the /tmp

sudo find /tmp/ -name .s.PGSQL.5432

If postgres is running and accepting socket connections, the above should tell you the location of the socket. On my machine, it turned out to be:

/tmp/.s.PGSQL.5432

Then, try connecting via psql using this file's location explicitly, eg.

psql -h /tmp/ dbname

Step 3: If the service is running but you don't see a socket

If you can't find the socket, but see that the service is running, Verify that the pg_hba.conf file allows local sockets.

Browse to the datadir and you should find the pg_hba.conf file.

By default, near the bottom of the file you should see the following lines:

# "local" is for Unix domain socket connections only
local       all       all       trust

If you don't see it, you can modify the file, and restart the postgres service.

How to generate random float number in C

You can also generate in a range [min, max] with something like

float float_rand( float min, float max )
{
    float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
    return min + scale * ( max - min );      /* [min, max] */
}

MAX function in where clause mysql

Use a subselect:

SELECT row  FROM table  WHERE id=(
    SELECT max(id) FROM table
)

Note: ID must be unique, else multiple rows are returned

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

Get jQuery version from inspecting the jQuery object

console.log( 'You are running jQuery version: ' + $.fn.jquery );

MassAssignmentException in Laravel

if you have table and fields on database you can simply use this command :

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

Why isn't my Pandas 'apply' function referencing multiple columns working?

If you just want to compute (column a) % (column b), you don't need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

Multiple GitHub Accounts & SSH Config

I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:


Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':

ssh-keygen -t rsa -C "[email protected]"


Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:

# Default GitHub
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# Work GitHub
Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_work


Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:

$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)

If your entries aren't there then run:

ssh-add ~/.ssh/id_rsa_work


Step 4: test
To test you've done this all correctly, I suggest the following quick check:

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)

Set an empty DateTime variable

Either:

DateTime dt = new DateTime();

or

DateTime dt = default(DateTime);

ComboBox.SelectedText doesn't give me the SelectedText

or try this code

 String status = "The status of my combobox is " + comboBoxTest.SelectedItem.ToString();

How do I create a basic UIButton programmatically?

You can just put the creator instance within a loop and dynamically add names from an array if you so wish.

PHP How to fix Notice: Undefined variable:

Xampp I guess you're using MySQL.

mysql_fetch_array($result);  

And make sure $result is not empty.

How to align an indented line in a span that wraps into multiple lines?

<!DOCTYPE html>
<html>
<body>

<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>

</body>
</html>

How can I turn a DataTable to a CSV?

Possibly, most easy way will be to use:

https://github.com/ukushu/DataExporter

especially in case of your data of datatable containing /r/n characters or separator symbol inside of your dataTable cells. Almost all of other answers will not work with such cells.

only you need is to write the following code:

Csv csv = new Csv("\t");//Needed delimiter 

var columnNames = dt.Columns.Cast<DataColumn>().
    Select(column => column.ColumnName).ToArray();

csv.AddRow(columnNames);

foreach (DataRow row in dt.Rows)
{
    var fields = row.ItemArray.Select(field => field.ToString()).ToArray;
    csv.AddRow(fields);   
}

csv.Save();

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Move to another EditText when Soft Keyboard Next is clicked on Android

If you want to use a multiline EditText with imeOptions, try:

android:inputType="textImeMultiLine"

Force IE8 Into IE7 Compatiblity Mode

There is an HTTP header you can set that will force IE8 to use IE7-compatibility mode.

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to make a JSON call to a url?

DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.

Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/

your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }

In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.

Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.

It works, in any case.

Here's my implementation of DickFeynman's approach, in the the client:

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>

I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.

More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.

find -exec with multiple commands

I usually embed the find in a small for loop one liner, where the find is executed in a subcommand with $().

Your command would look like this then:

for f in $(find *.txt); do echo "$(tail -1 $f), $(ls $f)"; done

The good thing is that instead of {} you just use $f and instead of the -exec … you write all your commands between do and ; done.

Not sure what you actually want to do, but maybe something like this?

for f in $(find *.txt); do echo $f; tail -1 $f; ls -l $f; echo; done

How to format a duration in java? (e.g format H:MM:SS)

I'm not sure that is you want, but check this Android helper class

import android.text.format.DateUtils

For example: DateUtils.formatElapsedTime()

Spring .properties file: get element as an Array

With a Spring Boot one can do the following:

application.properties

values[0]=abc
values[1]=def

Configuration class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties
public class Configuration {

    List<String> values = new ArrayList<>();

    public List<String> getValues() {
        return values;
    }

}

This is needed, without this class or without the values in class it is not working.

Spring Boot Application class

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);

    // notice #{} is used instead of ${}
    @Value("#{configuration.values}")
    List<String> values;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) {
        LOG.info("values: {}", values);
    }

}

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

How to connect to local instance of SQL Server 2008 Express

Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.

ASP.NET MVC View Engine Comparison

Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.

jQuery if statement, syntax

If you're using Jquery to manipulate the DOM, then I have found the following a good way to include logic in a Jquery statement:

$(selector).addClass(A && B?'classIfTrue':'');

How to enable CORS in ASP.NET Core

Some troubleshooting tips, after I managed to waste two hours on the most trivial CORS issue:

  1. If you see CORS policy execution failed logged... Don't assume that your CORS policy is not executing properly. In fact, the CORS middleware works, and your policy is executing properly. The only thing this badly worded message means is that the request's origin doesn't match any of the allowed origins (see source), i.e. the request is disallowed.

  2. The origin check (as of ASP.NET Core 5.0) happens in a very simple way... i.e. case-sensitive ordinal string comparison (see source) between the strings you provided via WithOrigins() and what exists in HttpContext.Request.Headers[Origin].

  3. CORS can fail if you set an allowed origin with a trailing slash /, or if it contains uppercase letters. (In my case I did in fact accidentally copy the host with a trailing slash.)

Go to particular revision

Using a commit's SHA1 key, you could do the following:

  • First, find the commit you want for a specific file:

    git log -n <# commits> <file-name>

    This, based on your <# commits>, will generate a list of commits for a specific file.

    TIP: if you aren't sure what commit you are looking for, a good way to find out is using the following command: git diff <commit-SHA1>..HEAD <file-name>. This command will show the difference between the current version of a commit, and a previous version of a commit for a specific file.

    NOTE: a commit's SHA1 key is formatted in the git log -n's list as:

commit <SHA1 id>

  • Second, checkout the desired version:

    If you have found the desired commit/version you want, simply use the command: git checkout <desired-SHA1> <file-name>

    This will place the version of the file you specified in the staging area. To take it out of the staging area simply use the command: reset HEAD <file-name>

To revert back to where the remote repository is pointed to, simply use the command: git checkout HEAD <file-name>

Adding POST parameters before submit

Previous answer can be shortened and be more readable.

$('#commentForm').submit(function () {
    $(this).append($.map(params, function (param) {
        return   $('<input>', {
            type: 'hidden',
            name: param.name,
            value: param.value
        })
    }))
});

Add data to JSONObject

The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.

What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!

I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.

So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;

//  create and initialize an object 
public static JSONObject buildObject( final SimpleEntry... entries ) { 
    JSONObject object = new JSONObject();
    for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
    return object;
}

//  nest a list of objects inside another                          
public static void putObjects( final JSONObject parentObject, final String key,
                               final JSONObject... objects ) { 
    List objectList = new ArrayList<JSONObject>();
    for( JSONObject o : objects ) objectList.add( o );
    parentObject.put( key, objectList );
}   

Implementation example:

JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
    buildObject( 
        new SimpleEntry( "child1Key1", "someValue" )
      , new SimpleEntry( "child1Key2", "someValue" ) 
    )
  , buildObject( 
        new SimpleEntry( "child2Key1", "someValue" )
      , new SimpleEntry( "child2Key2", "someValue" ) 
    )
);      

Does JavaScript have a built in stringbuilder class?

If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the + or += operator are extremely slow on IE. This is especially true for IE6. On modern browsers += is usually just as fast as array joins.

When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:

var html = [];
html.push(
  "<html>",
  "<body>",
  "bla bla bla",
  "</body>",
  "</html>"
);
return html.join("");

Note that the push methods accepts multiple arguments.

jQuery Determine if a matched class has a given id

I would probably use $('.mydiv').is('#foo'); That said if you know the Id why wouldnt you just apply it to the selector in the first place?

Django error - matching query does not exist

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return Comment.objects.get(pk=id)
    except Comment.DoesNotExist:
        return False

Is there a RegExp.escape function in JavaScript?

There has only ever been and ever will be 12 meta characters that need to be escaped to be considered a literal.

It doesn't matter what is done with the escaped string, inserted into a balanced regex wrapper or appended. It doesn't matter.

Do a string replace using this

var escaped_string = oldstring.replace(/[\\^$.|?*+()[{]/g, '\\$&');

Read a variable in bash with a default value

In Bash 4:

name="Ricardo"
read -e -i "$name" -p "Please enter your name: " input
name="${input:-$name}"

This displays the name after the prompt like this:

Please enter your name: Ricardo

with the cursor at the end of the name and allows the user to edit it. The last line is optional and forces the name to be the original default if the user erases the input or default (submitting a null).

How to remove constraints from my MySQL table?

Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field], because they can be altered.

Laravel for example uses [parent table]_[referencing field]_foreign as naming convention. You can show the names of the foreign keys by using this query, as shown here:

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';

Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.

How to unlock a file from someone else in Team Foundation Server

You need to be project admin or to have tfs account (user name/password) of the user who had locked the file.

in Visual Studio 2019:

  • Menu > View > Terminal (ctrl+`)
  • Wait until developer powershell or command prompt loads to the cursor like this:
    Drive:\your solution path>
  • you must undo changes to unlock the file:
    tf vc undo /workspace:"workspacename;worksapceowner" "$/path/[file.extension][*]" [/recursive] [/login:"user name,password"]
    example:-
    tf vc undo /workspace:"DESKTOP-F6BN2GHTKQ8;Johne123" "$/mywebsite/mywebsite/appsettings.json"

What's the difference between Invoke() and BeginInvoke()

Just to give a short, working example to see an effect of their difference

new Thread(foo).Start();

private void foo()
{
  this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    (ThreadStart)delegate()
    {
        myTextBox.Text = "bing";
        Thread.Sleep(TimeSpan.FromSeconds(3));
    });
  MessageBox.Show("done");
}

If use BeginInvoke, MessageBox pops simultaneous to the text update. If use Invoke, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (BeginInvoke) and a synchronous (Invoke) call.

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Stop all active ajax requests in jQuery

Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.

I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

Android REST client, Sample?

Never use AsynTask to perform network request or whatever that need to be persisted. Async Task are strongly tied to your activity and if the user change the orientation of the screen since the App is re created the AsyncTask will be stopped.

I suggest you to use Service pattern with Intent Service and ResultReceiver. Take a look to RESTDroid. It's a library that allows you to perform any kind of REST request asynchronously and notify your UI with Request Listeners implementing the Virgil Dobjanschi's service pattern.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

Angular 2 router no base href set

Check your index.html. If you have accidentally removed the following part, include it and it will be fine

<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

Can I use VARCHAR as the PRIMARY KEY?

A blanket "no you shouldn't" is terrible advice. This is perfectly reasonable in many situations depending on your use case, workload, data entropy, hardware, etc.. What you shouldn't do is make assumptions.

It should be noted that you can specify a prefix which will limit MySQL's indexing, thereby giving you some help in narrowing down the results before scanning the rest. This may, however, become less useful over time as your prefix "fills up" and becomes less unique.

It's very simple to do, e.g.:

CREATE TABLE IF NOT EXISTS `foo` (
  `id` varchar(128),
  PRIMARY KEY (`id`(4))
)

Also note that the prefix (4) appears after the column quotes. Where the 4 means that it should use the first 4 characters of the 128 possible characters that can exist as the id.

Lastly, you should read how index prefixes work and their limitations before using them: https://dev.mysql.com/doc/refman/8.0/en/create-index.html

Turn off enclosing <p> tags in CKEditor 3.0

I'm doing something I'm not proud of as workaround. In my Python servlet that actually saves to the database, I do:

if description.startswith('<p>') and description.endswith('</p>'):
    description = description[3:-4]

How can I convert an RGB image into grayscale in Python?

The fastest and current way is to use Pillow, installed via pip install Pillow.

The code is then:

from PIL import Image
img = Image.open('input_file.jpg').convert('L')
img.save('output_file.jpg')

C++11 thread-safe queue

This is probably how you should do it:

void push(std::string&& filename)
{
    {
        std::lock_guard<std::mutex> lock(qMutex);

        q.push(std::move(filename));
    }

    populatedNotifier.notify_one();
}

bool try_pop(std::string& filename, std::chrono::milliseconds timeout)
{
    std::unique_lock<std::mutex> lock(qMutex);

    if(!populatedNotifier.wait_for(lock, timeout, [this] { return !q.empty(); }))
        return false;

    filename = std::move(q.front());
    q.pop();

    return true;    
}

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

AngularJS directive does not update on scope variable changes

A simple solution is to make the scope variable object. Then access the content with {{ whatever-object.whatever-property }}. The variable is not updating because JavaScript pass Primitive type by value. Whereas Object are passed by reference which solves the problem.

Quotation marks inside a string

You can add escaped double quotes like this: String name = "\"john\"";

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

Python - Join with newline

When you print it with this print 'I\nwould\nexpect\nmultiple\nlines' you would get:

I
would
expect
multiple
lines

The \n is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.

How to install psycopg2 with "pip" on Python?

Psycopg2 Depends on Postgres Libraries. On Ubuntu You can use:

apt-get install libpq-dev

Then:

pip install psycopg2

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

How to use @Nullable and @Nonnull annotations more effectively?

Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:

    directPathToA(y);
                  ^
Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'

This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA() has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.

And when using a clever @NonNullByDefault we don't even have to say this every time.

In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.

How do I check if an element is hidden in jQuery?

Use class toggling, not style editing . . .

Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.


JavaScript Best Practices and Optimization

Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:

sorting a List of Map<String, String>

@Test
public void testSortedMaps() {
    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("name", "Josh");

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("name", "Anna");

    Map<String, String> map3 = new HashMap<String, String>();
    map3.put("name", "Bernie");

    List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
    mapList.add(map1);
    mapList.add(map2);
    mapList.add(map3);

    Collections.sort(mapList, new Comparator<Map<String, String>>() {
        public int compare(final Map<String, String> o1, final Map<String, String> o2) {
            return o1.get("name").compareTo(o2.get("name"));
        }
    });

    Assert.assertEquals("Anna", mapList.get(0).get("name"));
    Assert.assertEquals("Bernie", mapList.get(1).get("name"));
    Assert.assertEquals("Josh", mapList.get(2).get("name"));

}

Spring Boot not serving static content

Put static resources under the directory:

/src/main/resources/static

add this property in application.properties file

server.servlet.context-path=/pdx

You can access from http://localhost:8080/pdx/images/image.jpg

enter image description here

Understanding slice notation

The rules of slicing are as follows:

[lower bound : upper bound : step size]

I- Convert upper bound and lower bound into common signs.

II- Then check if the step size is a positive or a negative value.

(i) If the step size is a positive value, upper bound should be greater than lower bound, otherwise empty string is printed. For example:

s="Welcome"
s1=s[0:3:1]
print(s1)

The output:

Wel

However if we run the following code:

s="Welcome"
s1=s[3:0:1]
print(s1)

It will return an empty string.

(ii) If the step size if a negative value, upper bound should be lesser than lower bound, otherwise empty string will be printed. For example:

s="Welcome"
s1=s[3:0:-1]
print(s1)

The output:

cle

But if we run the following code:

s="Welcome"
s1=s[0:5:-1]
print(s1)

The output will be an empty string.

Thus in the code:

str = 'abcd'
l = len(str)
str2 = str[l-1:0:-1]    #str[3:0:-1] 
print(str2)
str2 = str[l-1:-1:-1]    #str[3:-1:-1]
print(str2)

In the first str2=str[l-1:0:-1], the upper bound is lesser than the lower bound, thus dcb is printed.

However in str2=str[l-1:-1:-1], the upper bound is not less than the lower bound (upon converting lower bound into negative value which is -1: since index of last element is -1 as well as 3).

How to assert greater than using JUnit Assert?

you can also try below simple soln:

previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";

Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);

Assert.assertTrue(prev  > curr );   

How to change the size of the radio button using CSS?

This works fine for me in all browsers:

(inline style for simplicity...)

<label style="font-size:16px;">
    <input style="height:1em; width:1em;" type="radio">
    <span>Button One</span>
</label>

The size of both the radio button and text will change with the label's font-size.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Tried all the above, use the Firebase Assistant! It is the simplest way to solve this. First remove all the dependencies you added to the build.gradle (using the manual method) and then in Android Studio:

Click Tools > Firebase to open the Assistant window.

It really is as easy as that.

How to install a specific version of a ruby gem?

For installing gem install gemname -v versionnumber

For uninstall gem uninstall gemname -v versionnumber

Difference between logger.info and logger.debug

What is the difference between logger.debug and logger.info?

These are only some default level already defined. You can define your own levels if you like. The purpose of those levels is to enable/disable one or more of them, without making any change in your code.

When logger.debug will be printed ??

When you have enabled the debug or any higher level in your configuration.

How to set selectedIndex of select element using display text?

Add name attribute to your option:

<option value="0" name="Chicken">Chicken</option>

With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one() {_x000D_
    function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
    alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
    alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
_x000D_
_x000D_

A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to terminate a python subprocess launched with shell=True

As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.

Extracting extension from filename in Python

try this:

files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']

for file in files: #1
    if (file.split(".")[-2] in pen_ext): #2
        ext =  file.split(".")[-2]+"."+file.split(".")[-1]#3
    else:
        ext = file.split(".")[-1] #4
    print (ext) #5
  1. get all file name inside the list
  2. splitting file name and check the penultimate extension, is it in the pen_ext list or not?
  3. if yes then join it with the last extension and set it as the file's extension
  4. if not then just put the last extension as the file's extension
  5. and then check it out

'Operation is not valid due to the current state of the object' error during postback

I didn't apply paging on my gridview and it extends to more than 600 records (with checkbox, buttons, etc.) and the value of 2001 didn't work. You may increase the value, say 10000 and test.

<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>

What's the scope of a variable initialized in an if statement?

And note that since Python types are only checked at runtime you can have code like:

if True:
    x = 2
    y = 4
else:
    x = "One"
    y = "Two"
print(x + y)

But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Convert a secure string to plain text

In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

 $UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]

Oracle date difference to get number of years

For Oracle SQL Developer I was able to calculate the difference in years using the below line of SQL. This was to get Years that were within 0 to 10 years difference. You can do a case like shown in some of the other responses to handle your ifs as well. Happy Coding!

TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

If you want to insert NULL only when the value is empty or '', but insert the value when it is available.

A) Receives the form data using POST method, and calls function insert with those values.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evaluates if a field was not filled up by the user, and inserts NULL if that's the case.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

For instance, if the user doesn't input anything on the productName field of the form, then $productName will be SET but EMPTY. So, you need check if it is empty(), and if it is, then insert NULL.

Tested on PHP 5.5.17

Good luck,

How to make a pure css based dropdown menu?

Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:

<ul>
    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;

        <ul>
            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>
        </ul>
    </li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>
</ul>

CSS:

* {
  margin: 0;
  padding: 0;
}

body {
  font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}

ul {
  width: 9em;
  list-style-type: none;
  font-size: 0.75em;
}

li {
  float: left;
  margin: 0 4px 4px 0;
  background: #60c;
  background: rgba(102, 0, 204, 0.66);
  border: 4px solid #60c;
  color: #fff;
}
li:hover {
  position: relative;
}

ul ul {
  z-index: 1;
  position: absolute;
  left: -999em;
  width: auto;
  background: #ccc;
  background: rgba(204, 204, 204, 0.33);
}

li:hover ul {
  top: 2em;
  left: 3px;
}

li li {
  margin: 0 0 3px 0;
  background: #909;
  background: rgba(153, 0, 153, 0.66);
  border: 3px solid #909;
}

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

In my case it was the university wifi blocking port 3306. I was able to connect by using a mobile hotspot.

Change to a mobile hotspot or another network, and if it works there, then you know that original network is blocking port 3306. If you get the same error on more than 1 network, then you know it's specific to your machine.

Illegal mix of collations error in MySql

Was getting Illegal mix of collations while creating a category in Bagisto. Running these commands (thank you @Quy Le) solved the issue for me:

--set utf8 for connection

SET collation_connection = 'utf8_general_ci'

--change CHARACTER SET of DB to utf8

ALTER DATABASE dbName CHARACTER SET utf8 COLLATE utf8_general_ci

--change category tables

ALTER TABLE categories CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

ALTER TABLE category_translations CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

Convert interface{} to int

Adding another answer that uses switch... There are more comprehensive examples out there, but this will give you the idea.

In example, t becomes the specified data type within each case scope. Note, you have to provide a case for only one type at a type, otherwise t remains an interface.

package main

import "fmt"

func main() {
    var val interface{} // your starting value
    val = 4

    var i int // your final value

    switch t := val.(type) {
    case int:
        fmt.Printf("%d == %T\n", t, t)
        i = t
    case int8:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int16:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int32:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int64:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case bool:
        fmt.Printf("%t == %T\n", t, t)
        // // not covertible unless...
        // if t {
        //  i = 1
        // } else {
        //  i = 0
        // }
    case float32:
        fmt.Printf("%g == %T\n", t, t)
        i = int(t) // standardizes across systems
    case float64:
        fmt.Printf("%f == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint8:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint16:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint32:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint64:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case string:
        fmt.Printf("%s == %T\n", t, t)
        // gets a little messy...
    default:
        // what is it then?
        fmt.Printf("%v == %T\n", t, t)
    }

    fmt.Printf("i == %d\n", i)
}