Programs & Examples On #Canonicalization

is a process for converting data that has more than one possible representation into a "standard", "normal", or canonical form.

"The system cannot find the file specified"

If you encounter this error in GoDaddy after deploying a .Net MVC web application..And your web.config is absolutely correct... Right click your data project select settings and make sure that the correct connection strings to the GoDaddy server is in use

How to determine if string contains specific substring within the first X characters

You can also use regular expressions (less readable though)

string regex = "^.{0,7}abc";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
string Value1 = "sssddabcgghh";

Console.WriteLine(reg.Match(Value1).Success);

How to get cookie expiration date / creation date from javascript?

you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs

Correct way to read a text file into a buffer in C?

Have you considered mmap()? You can read from the file directly as if it were already in memory.

http://beej.us/guide/bgipc/output/html/multipage/mmap.html

Python 2.7 getting user input and manipulating as string without quotations

My Working code with fixes:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
     print("Correct!")
     correct = True
else:
    print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
        print("Correct!")
        correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

print("Thanks for playing!")

What does "var" mean in C#?

"var" means the compiler will determine the explicit type of the variable, based on usage. For example,

var myVar = new Connection();

would give you a variable of type Connection.

How to correctly save instance state of Fragments in back stack?

I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.

Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible

MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
    }
}

Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.

@Override
public void onDestroyView() {
    super.onDestroyView();
    savedState = saveState();
    createdStateInDestroyView = true;
    myObject = null;
}

This part would be the same.

private Bundle saveState() { 
    Bundle state = new Bundle();
    state.putSerializable(SAVED_BUNDLE_TAG, myObject);
    return state;
}

Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.

    @Override
public void onSaveInstanceState(Bundle outState) {

    if (myObject == null) {
        outState.putBundle(SAVED_BUNDLE_TAG, savedState);
    } else {
        outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
    }
    createdStateInDestroyView = false;
    super.onSaveInstanceState(outState);
}

Now wherever you want to restore the state just use the savedState bundle

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    if(savedState != null) {
        myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
    }
    ...
}

How can I use a for each loop on an array?

Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something (element)
    Next element
End Sub


Sub do_something(ByVal e As String)

End Sub

The other option is to convert the variant to a string before passing it.

  do_something CStr(element)

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

How to use filter, map, and reduce in Python 3

Here are the examples of Filter, map and reduce functions.

numbers = [10,11,12,22,34,43,54,34,67,87,88,98,99,87,44,66]

//Filter

oddNumbers = list(filter(lambda x: x%2 != 0, numbers))

print(oddNumbers)

//Map

multiplyOf2 = list(map(lambda x: x*2, numbers))

print(multiplyOf2)

//Reduce

The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:

from functools import reduce

sumOfNumbers = reduce(lambda x,y: x+y, numbers)

print(sumOfNumbers)

whitespaces in the path of windows filepath

(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.

    aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '

    r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)

Count the items from a IEnumerable<T> without iterating?

I use such code, if I have list of strings:

((IList<string>)Table).Count

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

I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.

Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.

public interface IZeroWrapper<TNumber> {
  TNumber Zero {get;}
}

public class DoubleWrapper: IZeroWrapper<double> {
  public double Zero { get { return 0; } }
}

HTTP headers in Websockets client API

Sending Authorization header is not possible.

Attaching a token query parameter is an option. However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.

Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.

Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

git stash apply version

The keys into the stash are actually the stash@{n} items on the left. So try:

git stash apply stash@{0}

(note that in some shells you need to quote "stash@{0}", like zsh, fish and powershell).

Since version 2.11, it's pretty easy, you can use the N stack number instead of using stash@{n}. So now instead of using:

git stash apply "stash@{n}"

You can type:

git stash apply n

To get list of stashes:

git stash list

In fact stash@{0} is a revision in git that you can switch to... but git stash apply ... should figure out how to DTRT to apply it to your current location.

unique object identifier in javascript

Actually, you don't need to modify the object prototype and add a function there. The following should work well for your purpose.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

npm WARN package.json: No repository field

It's just a check as of NPM v1.2.20, they report this as a warning.

However, don't worry, there are sooooooo many packages which still don't have the repository field in their package.json. The field is used for informational purposes.

In the case you're a package author, put the repository in your package.json, like this:

"repository": {
  "type": "git",
  "url": "git://github.com/username/repository.git"
}

Read more about the repository field, and see the logged bug for further details.


Additionally, as originally reported by @dan_nl, you can set private key in your package.json.
This will not only stop you from accidentally running npm publish in your app, but will also stop NPM from printing warnings regarding package.json problems.

{
  "name": "my-super-amazing-app",
  "version": "1.0.0",
  "private": true
}

Raise an error manually in T-SQL to jump to BEGIN CATCH block

you can use raiserror. Read more details here

--from MSDN

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

EDIT If you are using SQL Server 2012+ you can use throw clause. Here are the details.

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

OraOLEDB.Oracle provider is not registered on the local machine

Do the following test:

Open a Command Prompt and type: tnsping instance_name

where instance_name is the name of the instance you want to connect (if it's a XE database, use "tnsping xe"

If it returns ok, follow steps of Der Wolf's answer. If doesn't return ok, follow steps of Annjawn's answer.

It solved for me in both cases.

CSS: 100% width or height while keeping aspect ratio?

I use this for a rectangular container with height and width fixed, but with images of different sizes.

img {
  max-width: 95%;
  max-height: 15em;
  width: auto !important;
}

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Using Python 3 in virtualenv

virtualenv --python=/usr/bin/python3 <name of env>

worked for me.

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

How to prevent "The play() request was interrupted by a call to pause()" error?

Depending on how complex you want your solution, this may be useful:

var currentPromise=false;    //Keeps track of active Promise

function playAudio(n){
    if(!currentPromise){    //normal behavior
        n.pause();
        n.currentTime = 0;
        currentPromise = n.play();    //Calls play. Will store a Promise object in newer versions of chrome;
                                      //stores undefined in other browsers
        if(currentPromise){    //Promise exists
            currentPromise.then(function(){ //handle Promise completion
                promiseComplete(n);
            });
        }
    }else{    //Wait for promise to complete
        //Store additional information to be called
        currentPromise.calledAgain = true;
    }
}

function promiseComplete(n){
    var callAgain = currentPromise.calledAgain;    //get stored information
    currentPromise = false;    //reset currentPromise variable
    if(callAgain){
        playAudio(n);
    }
}

This is a bit overkill, but helps when handling a Promise in unique scenarios.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Update 2018 (as of Bootstrap 4.1)

Yes, pull-left and pull-right have been replaced with float-left and float-right in Bootstrap 4.

However, floats will not work in all cases since Bootstrap 4 is now flexbox.

To align flexbox children to the right, use auto-margins (ie: ml-auto) or the flexbox utils (ie: justify-content-end, align-self-end, etc..).

Examples

Navs:

<ul class="nav">
   <li><a href class="nav-link">Link</a></li>
   <li><a href class="nav-link">Link</a></li>
   <li class="ml-auto"><a href class="nav-link">Right</a></li>
</ul>

Breadcrumbs:

<ul class="breadcrumb">
    <li><a href="/">Home</a></li>
    <li class="active"><a href="/">Link</a></li>
    <li class="ml-auto"><a href="/">Right</a></li>
</ul>

https://www.codeply.com/go/6ITgrV7pvL

Grid:

<div class="row">
    <div class="col-3">Left</div>
    <div class="col-3 ml-auto">Right</div>
</div>

Including all the jars in a directory within the Java classpath

Correct:

java -classpath "lib/*:." my.package.Program

Incorrect:

java -classpath "lib/a*.jar:." my.package.Program
java -classpath "lib/a*:."     my.package.Program
java -classpath "lib/*.jar:."  my.package.Program
java -classpath  lib/*:.       my.package.Program

How to match a substring in a string, ignoring case

a = "MandY"
alow = a.lower()
if "mandy" in alow:
    print "true"

work around

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

My solution is that i want data from all docs and i dont want _id, so

User.find({}, {_id:0, keyToShow:1, keyToNotShow:0})

Insert images to XML file

Since XML is a text format and images are usually not (except some ancient and archaic formats) there is no really sensible way to do it. Looking at things like ODT or OOXML also shows you that they don't embed images directly into XML.

What you can do, however, is convert it to Base64 or similar and embed it into the XML.

XML's whitespace handling may further complicate things in such cases, though.

Can someone give an example of cosine similarity, in a very simple, graphical way?

Two Vectors A and B exists in a 2D space or 3D space, the angle between those vectors is cos similarity.

If the angle is more (can reach max 180 degree) which is Cos 180=-1 and the minimum angle is 0 degree. cos 0 =1 implies the vectors are aligned to each other and hence the vectors are similar.

cos 90=0 (which is sufficient to conclude that the vectors A and B are not similar at all and since distance cant be negative, the cosine values will lie from 0 to 1. Hence, more angle implies implies reducing similarity (visualising also it makes sense)

Initialize class fields in constructor or at declaration?

Not a direct answer to your question about the best practice but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).

class MyGeneric<T>
{
    T data;
    //T data = ""; // <-- ERROR
    //T data = 0; // <-- ERROR
    //T data = null; // <-- ERROR        

    public MyGeneric()
    {
        // All of the above errors would be errors here in constructor as well
    }
}

And the special method to initialize a generic field to its default value is the following:

class MyGeneric<T>
{
    T data = default(T);

    public MyGeneric()
    {           
        // The same method can be used here in constructor
    }
}

Age from birthdate in python

That can be done much simpler considering that int(True) is 1 and int(False) is 0:

from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

Create tap-able "links" in the NSAttributedString of a UILabel?

In general, if we want to have a clickable link in text displayed by UILabel, we would need to resolve two independent tasks:

  1. Changing the appearance of a portion of the text to look like a link
  2. Detecting and handling touches on the link (opening an URL is a particular case)

The first one is easy. Starting from iOS 6 UILabel supports display of attributed strings. All you need to do is to create and configure an instance of NSMutableAttributedString:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"String with a link" attributes:nil];
NSRange linkRange = NSMakeRange(14, 4); // for the word "link" in the string above

NSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0],
                                  NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };
[attributedString setAttributes:linkAttributes range:linkRange];

// Assign attributedText to UILabel
label.attributedText = attributedString;

That's it! The code above makes UILabel to display String with a link

Now we should detect touches on this link. The idea is to catch all taps within UILabel and figure out whether the location of the tap was close enough to the link. To catch touches we can add tap gesture recognizer to the label. Make sure to enable userInteraction for the label, it's turned off by default:

label.userInteractionEnabled = YES;
[label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnLabel:)]]; 

Now the most sophisticated stuff: finding out whether the tap was on where the link is displayed and not on any other portion of the label. If we had single-lined UILabel, this task could be solved relatively easy by hardcoding the area bounds where the link is displayed, but let's solve this problem more elegantly and for general case - multiline UILabel without preliminary knowledge about the link layout.

One of the approaches is to use capabilities of Text Kit API introduced in iOS 7:

// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];

// Configure layoutManager and textStorage
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

// Configure textContainer
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = label.lineBreakMode;
textContainer.maximumNumberOfLines = label.numberOfLines;

Save created and configured instances of NSLayoutManager, NSTextContainer and NSTextStorage in properties in your class (most likely UIViewController's descendant) - we'll need them in other methods.

Now, each time the label changes its frame, update textContainer's size:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.textContainer.size = self.label.bounds.size;
}

And finally, detect whether the tap was exactly on the link:

- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture
{
    CGPoint locationOfTouchInLabel = [tapGesture locationInView:tapGesture.view];
    CGSize labelSize = tapGesture.view.bounds.size;
    CGRect textBoundingBox = [self.layoutManager usedRectForTextContainer:self.textContainer];
    CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
    CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                         locationOfTouchInLabel.y - textContainerOffset.y);
    NSInteger indexOfCharacter = [self.layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                            inTextContainer:self.textContainer
                                   fractionOfDistanceBetweenInsertionPoints:nil];
    NSRange linkRange = NSMakeRange(14, 4); // it's better to save the range somewhere when it was originally used for marking link in attributed string
    if (NSLocationInRange(indexOfCharacter, linkRange)) {
        // Open an URL, or handle the tap on the link in any other way
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://stackoverflow.com/"]];
    }
}

Oracle date "Between" Query

You need to convert those to actual dates instead of strings, try this:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('2010-01-15','YYYY-MM-DD') AND TO_DATE('2010-01-17', 'YYYY-MM-DD');

Edited to deal with format as specified:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('15-JAN-10','DD-MON-YY') AND TO_DATE('17-JAN-10','DD-MON-YY');

How to get past the login page with Wget?

Based on the manual page:

# Log in to the server.  This only needs to be done once.
wget --save-cookies cookies.txt \
     --keep-session-cookies \
     --post-data 'user=foo&password=bar' \
     --delete-after \
     http://server.com/auth.php

# Now grab the page or pages we care about.
wget --load-cookies cookies.txt \
     http://server.com/interesting/article.php

Make sure the --post-data parameter is properly percent-encoded (especially ampersands!) or the request will probably fail. Also make sure that user and password are the correct keys; you can find out the correct keys by sleuthing the HTML of the login page (look into your browser’s “inspect element” feature and find the name attribute on the username and password fields).

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Export MySQL data to Excel in PHP

Try this code. It's definitly working.

<?php
// Connection 

$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('excel',$conn);

$filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$user_query = mysql_query('select name,work from info');
// Write data to file
$flag = false;
while ($row = mysql_fetch_assoc($user_query)) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        $flag = true;
    }
    echo implode("\t", array_values($row)) . "\r\n";
}
?>

How to prevent robots from automatically filling up a form?

An easy-to-implement but not fool-proof (especially on "specific" attacks) way of solving anti-spam is tracking the time between form-submit and page-load.

Bots request a page, parse the page and submit the form. This is fast.

Humans type in a URL, load the page, wait before the page is fully loaded, scroll down, read content, decide wether to comment/fill in the form, require time to fill in the form, and submit.

The difference in time can be subtle; and how to track this time without cookies requires some way of server-side database. This may be an impact in performance.
Also you need to tweak the threshold-time.

Java Compare Two Lists

Are these really lists (ordered, with duplicates), or are they sets (unordered, no duplicates)?

Because if it's the latter, then you can use, say, a java.util.HashSet<E> and do this in expected linear time using the convenient retainAll.

    List<String> list1 = Arrays.asList(
        "milan", "milan", "iga", "dingo", "milan"
    );
    List<String> list2 = Arrays.asList(
        "hafil", "milan", "dingo", "meat"
    );

    // intersection as set
    Set<String> intersect = new HashSet<String>(list1);
    intersect.retainAll(list2);
    System.out.println(intersect.size()); // prints "2"
    System.out.println(intersect); // prints "[milan, dingo]"

    // intersection/union as list
    List<String> intersectList = new ArrayList<String>();
    intersectList.addAll(list1);
    intersectList.addAll(list2);
    intersectList.retainAll(intersect);
    System.out.println(intersectList);
    // prints "[milan, milan, dingo, milan, milan, dingo]"

    // original lists are structurally unmodified
    System.out.println(list1); // prints "[milan, milan, iga, dingo, milan]"
    System.out.println(list2); // prints "[hafil, milan, dingo, meat]"

How do I center list items inside a UL element?

li{
    display:table;
    margin:0px auto 0px auto;
}

This should work.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I resolved the same issue by running Workbench as administrator.

...I guess it's because of restrictions on company computers, in my case...

Android Animation Alpha

Hm...

The thing is wrong, and possibly in the proper operation of the animations in the Android API.

The fact is that when you set in your code alpha value of 0.2f is based on the settings in the xml file for android it means that :

0.2f = 0.2f of 0.2f (20% from 100%) ie from 0.2f / 5 = 0.04f
1f = 0.2f

So your animation in fact works from 0.04f to 0.2f

flag setFillAfter(true) certainly works, but you need to understand that at the end of your animation ImageView will have the alpha value 0.2f instead of one, because you specify 0.2f as marginally acceptable value in the animation (a kind of maximum alpha channel).

So if you want to have the desired result shall carry all your logic to your code and manipulate animations in code instead of determining in xml.

You should understand that your animations directly depends of two things:

  • LayoutParams of Animated View
  • Animation parameters.

Animation parameters manipulate your LayoutParams in setFillAfter\setFillBefore methods.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Scaling to double and bringing down to half with zoom worked for me.

transform: scale(2);
zoom: 0.5;

How to get the pure text without HTML element using JavaScript?

If you can use jquery then its simple

$("#txt").text()

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

How to get a thread and heap dump of a Java process on Windows that's not running in a console

If you can't (or don't want) to use the console/terminal for some reason, there is an alternative solution. You can make the Java application print the thread dump for you. The code that collects the Stack Trace is reasonable simple and can be attached to a button or a web interface.

private static String getThreadDump() {
    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();

    StringBuilder out = new StringBuilder();
    for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
        Thread thread = entry.getKey();
        StackTraceElement[] elements = entry.getValue();
        out.append(String.format("%s | prio=%d | %s", thread.getName(), thread.getPriority(), thread.getState()));
        out.append('\n');

        for (StackTraceElement element : elements) {
            out.append(element.toString()).append('\n');
        }
        out.append('\n');
    }
    return out.toString();
}

This method will return a string that looks like this:

main | prio=5 | RUNNABLE
java.lang.Thread.dumpThreads(Native Method)
java.lang.Thread.getAllStackTraces(Thread.java:1607)
Main.getThreadDump(Main.java:8)
Main.main(Main.java:36)

Monitor Ctrl-Break | prio=5 | RUNNABLE
java.net.PlainSocketImpl.initProto(Native Method)
java.net.PlainSocketImpl.<clinit>(PlainSocketImpl.java:45)
java.net.Socket.setImpl(Socket.java:503)
java.net.Socket.<init>(Socket.java:424)
java.net.Socket.<init>(Socket.java:211)
com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:59)

Finalizer | prio=8 | WAITING
java.lang.Object.wait(Native Method)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

Reference Handler | prio=10 | WAITING
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:502)
java.lang.ref.Reference.tryHandlePending(Reference.java:191)
java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

For those interested in a Java 8 version with streams, the code is even more compact:

private static String getThreadDump() {
    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    StringBuilder out = new StringBuilder();
    allStackTraces.forEach((thread, elements) -> {
        out.append(String.format("%s | prio=%d | %s", thread.getName(), thread.getPriority(), thread.getState()));
        out.append('\n');

        Arrays.stream(elements).forEach(element -> out.append(element.toString()).append('\n'));
        out.append('\n');
    });
    return out.toString();
}

You can easily test this code with:

System.out.print(getThreadDump());

How to determine the version of android SDK installed in computer?

In the case of Linux, You get the version of Android SDK using sdkmanager.

your_path/android-sdk/tools/bin/sdkmanager --version

in my case

/var/lib/jenkins/android-sdk/tools/bin/sdkmanager --versionenter image description here

How can I see normal print output created during pytest run?

The other answers don't work. The only way to see the captured output is using the following flag:

pytest --show-capture all

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.

 MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);

Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

HTML button to NOT submit form

For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.

Counting the Number of keywords in a dictionary in python

Calling len() directly on your dictionary works, and is faster than building an iterator, d.keys(), and calling len() on it, but the speed of either will negligible in comparison to whatever else your program is doing.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Permission denied at hdfs

For Hadoop 3.x, if you try to create a file on HDFS when unauthenticated (e.g. user=dr.who) you will get this error.

It is not recommended for systems that need to be secure, however if you'd like to disable file permissions entirely in Hadoop 3 the hdfs-site.xml setting has changed to:

<property>
  <name>dfs.permissions.enabled</name>
  <value>false</value>
</property>

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml

How to execute a Windows command on a remote PC?

If you are in a domain environment, you can also use:

winrs -r:PCNAME cmd

This will open a remote command shell.

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

Double border with different color

Use of pseudo-element as suggested by Terry has one PRO and one CON:

  1. PRO - great cross-browser compatibility because pseudo-element are supported also on older IE.
  2. CON - it requires to create an extra (even if generated) element, that infact is defined pseudo-element.

Anyway is a great solution.


OTHER SOLUTIONS:

If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:

  1. using outline property combined with border and a single inset box-shadow
  2. using two box-shadow combined with border.

Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border class):

.left
{
  outline: 4px solid #fff;
  box-shadow:inset 0 0 0 4px #fff;
}

.right
{
  box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}

LESS code:

You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.

Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):

@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;

.double-border 
{
  background-color: @content-color;
  border: @double-border-size solid @content-color;
  padding: 2em;
  width: 16em;
  height: 16em;
  float:left;
  margin-right:20px;
  text-align:center;
}

.left
{
  outline: @double-border-size solid @inset-border-color;
  box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}

.right
{
  box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

U can use

  $(document).on('click','p.class',function(e){
   e.preventDefault();
      //Code 
   });

Making a div vertically scrollable using CSS

You have it covered aside from using the wrong property. The scrollbar can be triggered with any property overflow, overflow-x, or overflow-y and each can be set to any of visible, hidden, scroll, auto, or inherit. You are currently looking at these two:

  • auto - This value will look at the width and height of the box. If they are defined, it won't let the box expand past those boundaries. Instead (if the content exceeds those boundaries), it will create a scrollbar for either boundary (or both) that exceeds its length.

  • scroll - This values forces a scrollbar, no matter what, even if the content does not exceed the boundary set. If the content doesn't need to be scrolled, the bar will appear as "disabled" or non-interactive.

If you always want the vertical scrollbar to appear:

You should use overflow-y: scroll. This forces a scrollbar to appear for the vertical axis whether or not it is needed. If you can't actually scroll the context, it will appear as a"disabled" scrollbar.

If you only want a scrollbar to appear if you can scroll the box:

Just use overflow: auto. Since your content by default just breaks to the next line when it cannot fit on the current line, a horizontal scrollbar won't be created (unless it's on an element that has word-wrapping disabled). For the vertical bar,it will allow the content to expand up to the height you have specified. If it exceeds that height, it will show a vertical scrollbar to view the rest of the content, but will not show a scrollbar if it does not exceed the height.

Mobile Redirect using htaccess

I modified Tim Stone's solution even further. This allows the cookie to be in 2 states, 1 for mobile and 0 for full. When the mobile cookie is set to 0 even a mobile browser will go to the full site.

Here is the code:

<IfModule mod_rewrite.c>
    RewriteBase /
    RewriteEngine On

    # Check if mobile=1 is set and set cookie 'mobile' equal to 1
    RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
    RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

    # Check if mobile=0 is set and set cookie 'mobile' equal to 0
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

    # cookie can't be set and read in the same request so check
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [S=1]

    # Check if this looks like a mobile device
    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
    RewriteCond %{HTTP:Profile}       !^$

    # Check if we're not already on the mobile site
    RewriteCond %{HTTP_HOST}          !^m\.
    # Check to make sure we haven't set the cookie before
    RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
    # Now redirect to the mobile site
    RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

Stopping a CSS3 Animation on last frame

Nobody actualy brought it so, the way it was made to work is animation-play-state set to paused.

Command to close an application of console?

So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.

        Console.WriteLine("College File Processor");
        Console.WriteLine("*************************************");
        Console.WriteLine("(H)elp");
        Console.WriteLine("Process (W)orkouts");
        Console.WriteLine("Process (I)nterviews");
        Console.WriteLine("Process (P)ro Days");
        Console.WriteLine("(S)tart Processing");
        Console.WriteLine("E(x)it");
        Console.WriteLine("*************************************");

        string response = "";
        string videotype = "";
        bool starting = false;
        bool exiting = false;

        response = Console.ReadLine();

        while ( response != "" )
        {
            switch ( response  )
            {
                case "H":
                case "h":
                    DisplayHelp();
                    break;

                case "W":
                case "w":
                    Console.WriteLine("Video Type set to Workout");
                    videotype = "W";
                    break;

                case "I":
                case "i":
                    Console.WriteLine("Video Type set to Interview");
                    videotype = "I";
                    break;

                case "P":
                case "p":
                    Console.WriteLine("Video Type set to Pro Day");
                    videotype = "P";
                    break;

                case "S":
                case "s":
                    if ( videotype == "" )
                    {
                        Console.WriteLine("Please Select Video Type Before Starting");
                    }
                    else
                    {
                        Console.WriteLine("Starting...");
                        starting = true;
                    }
                    break;

                case "E":
                case "e":
                    Console.WriteLine("Good Bye!");
                    System.Threading.Thread.Sleep(100);
                    exiting = true;
                    break;
            }

            if ( starting || exiting)
            {
                break;
            }
            else
            {
                response = Console.ReadLine();
            }
        }

        if ( starting )
        {
            ProcessFiles();
        }

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

ASP.NET MVC 3 Razor - Adding class to EditorFor

Adding a class to Html.EditorFor doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

@Html.EditorFor(x => x.Created)

and in the custom template:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>

How can I print literal curly-brace characters in a string and also use .format on it?

Reason is , {} is the syntax of .format() so in your case .format() doesn't recognize {Hello} so it threw an error.

you can override it by using double curly braces {{}},

x = " {{ Hello }} {0} "

or

try %s for text formatting,

x = " { Hello } %s"
print x%(42)  

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

How to run Conda?

I had same issue. What I did, removed anaconda directory from the install location and re-install after that it worked as I anticipated

Switch with if, else if, else, and loops inside case

but i only wanted the for statement to be attached to the if statement, not the else if statements as well.

Well get rid of the else then. If the else if is not supposed to be part of the for then write it as:

           for(int i=0; i<something_in_the_array.length;i++)
                if(whatever_value==(something_in_the_array[i]))
                {
                    value=2;
                    break;
                }

           if(whatever_value==2)
           {
                value=3;
                break;  // redundant now
           }

           else if(whatever_value==3)
           {
                value=4;
                break;  // redundant now
           }

Having said that:

  • it is not at all clear what you are really trying to do here,
  • not having the else part in the loop doesn't seem to make a lot of sense here,
  • a lot of people (myself included) think it is to always use braces ... so that people don't get tripped up by incorrect indentation when reading your code. (And in this case, it might help us figure out what you are really trying to do here ...)

Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.

  if (something) {
     doSomething();
  }

rather than:

  if (something) 
  {
     doSomething();
  }

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

I know that this is an old question but I am just going to place this here:

To prevent skype from using port 80 and port 443, open the Skype window, then click on the Tools menu and select Options.
Click on the Advanced tab, and go to the Connection sub-tab.
Uncheck the checkbox for Use port 80 and 443 as an alternative for additional incoming connections option.
Click on the Save button and then restart Skype.
After you restart skype, skype wont use port 88 or 443 anymore.

Hope this might help someone.

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

$.each(JSON.parse(myData), ...);

Sorting int array in descending order

If it's not a big/long array just mirror it:

for( int i = 0; i < arr.length/2; ++i ) 
{ 
  temp = arr[i]; 
  arr[i] = arr[arr.length - i - 1]; 
  arr[arr.length - i - 1] = temp; 
}

Keep overflow div scrolled to bottom unless user scrolls up

I couldn't get the top two answers to work, and none of the other answers were helpful to me. So I paid three people $30 from Reddit r/forhire and Upwork and got some really good answers. This answer should save you $90.



Justin Hundley / The Site Bros' solution

HTML

<div id="chatscreen">
  <div id="inner">
  
  </div>
</div>

CSS

#chatscreen {
  width: 300px;
  overflow-y: scroll;
  max-height:100px;
}

Javascript

$(function(){
    var scrolled = false;
  var lastScroll = 0;
  var count = 0;
    $("#chatscreen").on("scroll", function() {
    var nextScroll = $(this).scrollTop();

    if (nextScroll <= lastScroll) {
        scrolled = true;
    }
    lastScroll = nextScroll;
    
    console.log(nextScroll, $("#inner").height())
    if ((nextScroll + 100) == $("#inner").height()) {
        scrolled = false;
    }
  });
 
  function updateScroll(){
      if(!scrolled){
          var element = document.getElementById("chatscreen");
          var inner = document.getElementById("inner");
          element.scrollTop = inner.scrollHeight;
      }
  }

  // Now let's load our messages
  function load_messages(){
      $( "#inner" ).append( "Test" + count + "<br/>" );
      count = count + 1;
      updateScroll();
  }

    setInterval(load_messages,300); 
});

Preview the site bros' solution

portfolio



Lermex / Sviatoslav Chumakov's solution

HTML

<div id="chatscreen">

</div>

CSS

#chatscreen {
  height: 300px;
  border: 1px solid purple;
  overflow: scroll;
}

Javascript

$(function(){
var isScrolledToBottom = false;
// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
    updateScr();
}

var out = document.getElementById("chatscreen");
var c = 0;

$("#chatscreen").on('scroll', function(){
        console.log(out.scrollHeight);
    isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 10;
});

function updateScr() {
        // allow 1px inaccuracy by adding 1
    //console.log(out.scrollHeight - out.clientHeight,  out.scrollTop + 1);
    var newElement = document.createElement("div");

    newElement.innerHTML = c++;
    out.appendChild(newElement);
    
    console.log(isScrolledToBottom);

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}

var add = setInterval(updateScr, 1000);

setInterval(load_messages,300); // change to 300 to show the latest message you sent after pressing enter // comment this line and it works, uncomment and it fails
                                // leaving it on 1000 shows the second to last message
setInterval(updateScroll,30);
});

Preview Sviatoslav's solution

portfolio



Igor Rusinov's Solution

HTML

<div id="chatscreen"></div>

CSS

#chatscreen {
  height: 100px;
  overflow: scroll;
  border: 1px solid #000;
}

Javascript

$(function(){

// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
}

var out = document.getElementById("chatscreen");
var c = 0;
var add = setInterval(function() {
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
    load_messages();

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}, 1000);
setInterval(updateScroll,30);
});

Preview Igor's solution

portfolio

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

'Access denied for user 'root'@'localhost' (using password: NO)'

This is basically a more detailed version of a previous answer.

In your Terminal, go to the location of your utility program, mysqladmin

For example, if you were doing local development and using an application like M/W/XAMP, you might go to the directory:

/Applications/MAMP/Library/bin

This is where mysqladmin resides.

If you're not using an application like MAMP, you may also be able to find your local installation of mysql at: /usr/local/mysql

And then if you go to: /usr/local/mysql/bin/

You are in the directory where mysqladmin resides.

Then, to change the password, you will do the following:

  1. At your Terminal prompt enter the exact command below (aka copy and paste) and press enter. The word "password" is part of the command, so don't be confused and come to the conclusion that you need to replace this word with some password you created previously or want to use in the future. You will have a chance to enter a new password soon enough, but it's not in this first command that you will do that:

    ./mysqladmin -u root -p password

  2. The Terminal will ask you to enter your original or initial password, not a new one yet. From the above image you provided, it looks like you have one already created, so enter it here:

Enter password: oldpassword

  1. The Terminal will ask you to enter a new password. Type it here and press enter:

New password: newpassword

  1. Then the Terminal will ask you to confirm the new password. Type it here and press enter:

Confirm new password: newpassword

Reset or restart your Terminal.

In some cases, as with M/W/XAMP, you will have to update this new password in various files in order to get your application running properly again.

Replace all elements of Python NumPy Array that are greater than some value

Lets us assume you have a numpy array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
_x000D_
_x000D_

Note this will however modify the original array to avoid overwriting the original array try using arr.copy() to create a new detached copy of the original array and modify that instead.

_x000D_
_x000D_
import numpy as np

my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array

my_arr_copy[my_arr_copy > 10] = 0 
_x000D_
_x000D_
_x000D_

How to check if an option is selected?

If you need to check option selected state for specific value:

$('#selectorId option[value=YOUR_VALUE]:selected')

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

Your content must have a ListView whose id attribute is 'android.R.id.list'

Exact way I fixed this based on feedback above since I couldn't get it to work at first:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.preferences);

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
    android:key="upgradecategory"
    android:title="Upgrade" >
    <Preference
        android:key="download"
        android:title="Get OnCall Pager Pro"
        android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>

Java - How to create new Entry (key, value)

Why Map.Entry? I guess something like a key-value pair is fit for the case.

Use java.util.AbstractMap.SimpleImmutableEntry or java.util.AbstractMap.SimpleEntry

How to loop through all the properties of a class?

Use Reflection:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}

for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list

Edit: You can also specify a BindingFlags value to type.GetProperties():

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).

You don't need to specify BindingFlags.GetProperty, you use that when calling type.InvokeMember() to get the value of a property.

MySQL VARCHAR size?

100 characters.

This is the var (variable) in varchar: you only store what you enter (and an extra 2 bytes to store length upto 65535)

If it was char(200) then you'd always store 200 characters, padded with 100 spaces

See the docs: "The CHAR and VARCHAR Types"

Android MediaPlayer Stop and Play

According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.

vagrant login as root by default

Dont't forget root is allowed root to login before!!!

Place the config code below in /etc/ssh/sshd_config file.

PermitRootLogin yes

How to fix HTTP 404 on Github Pages?

I did all the tricks here on My Fork to fix page 404 on Github Page but it kept 404'ing.

Finaly found that my browser hardly keep the 10 minutes cache before it up on the web.

Just add /index.html into the end of URL then it showed up and solved the case.

https://username.github.io/index.html

@synthesize vs @dynamic, what are the differences?

One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.

Which type of folder structure should be used with Angular 2?

I’ve been using ng cli lately, and it was really tough to find a good way to structure my code.

The most efficient one I've seen so far comes from mrholek repository (https://github.com/mrholek/CoreUI-Angular).

This folder structure allows you to keep your root project clean and structure your components, it avoids redundant (sometimes useless) naming convention of the official Style Guide.

Also it’s, this structure is useful to group import when it’s needed and avoid having 30 lines of import for a single file.

src
|
|___ app
|
|   |___ components/shared
|   |   |___ header
|   |
|   |___ containers/layout
|   |   |___ layout1
|   |
|   |___ directives
|   |   |___ sidebar
|   |
|   |___ services
|   |   |___ *user.service.ts* 
|   | 
|   |___ guards
|   |   |___ *auth.guard.ts* 
|   |
|   |___ views
|   |   |___ about  
|   |
|   |___ *app.component.ts*
|   |
|   |___ *app.module.ts*
|   |
|   |___ *app.routing.ts*
|
|___ assets
|
|___ environments
|
|___ img
|   
|___ scss
|
|___ *index.html*
|
|___ *main.ts*

Python: How to pip install opencv2 with specific version 2.4.9?

you can try this

pip install opencv==2.4.9

SQL Server - Case Statement

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar. You could put your calculation into a derived table:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

A common table expression would work just as well:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

Angular 2 @ViewChild annotation returns undefined

The solution which worked for me was to add the directive in declarations in app.module.ts

Convert a positive number to negative in C#

int myInt = - System.Math.Abs(-5);

Display two fields side by side in a Bootstrap Form

@KyleMit answer is one way to solve this, however we may chose to avoid the undivided input fields acheived by input-group class. A better way to do this is by using form-group and row classes on a parent div and use input elements with grid-system classes provided by bootstrap.

<div class="form-group row">
    <input class="form-control col-md-6" type="text">
    <input class="form-control col-md-6" type="text">
</div>

Spring JSON request getting 406 (not Acceptable)

Make sure that following 2 jar's are present in class path.

If any one or both are missing then this error will come.

jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

Oracle JDBC intermittent Connection Issue

-Djava.security.egd=file:/dev/./urandom should be right! not -Djava.security.egd=file:/dev/../dev/urandom or -Djava.security.egd=file:///dev/urandom

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

None of the solution worked. You have to recompile your python again; once all the required packages were completely installed.

Follow this:

  1. Install required packages
  2. Run ./configure --enable-optimizations

https://gist.github.com/jerblack/798718c1910ccdd4ede92481229043be

git ignore vim temporary files

sure,

just have to create a ".gitignore" on the home directory of your project and have to contain

*.swp

that's it

in one command

project-home-directory$ echo '*.swp' >> .gitignore

Can a CSS class inherit one or more other classes?

Yes, but not exactly with that syntax.

.composite,
.something { display:inline }

.composite,
.else      { background:red }

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Is it possible to view RabbitMQ message contents directly from the command line?

a bit late to this, but yes rabbitmq has a build in tracer that allows you to see the incomming messages in a log. When enabled, you can just tail -f /var/tmp/rabbitmq-tracing/.log (on mac) to watch the messages.

the detailed discription is here http://www.mikeobrien.net/blog/tracing-rabbitmq-messages

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

How can I check if an ip is in a network in Python?

previous solution have a bug in ip & net == net. Correct ip lookup is ip & netmask = net

bugfixed code:

import socket
import struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def addressInNetwork(ip,net,netmask):
   "Is an address in a network"
   print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
   return ip & netmask == net

def humannetcheck(ip,net):
        address=dottedQuadToNum(ip)
        netaddr=dottedQuadToNum(net.split("/")[0])
        netmask=makeMask(long(net.split("/")[1]))
        return addressInNetwork(address,netaddr,netmask)


print humannetcheck("192.168.0.1","192.168.0.0/24");
print humannetcheck("192.169.0.1","192.168.0.0/24");

Sublime Text 2 - View whitespace characters

If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces

Update R using RStudio

You install a new version of R from the official website.

RStudio should automatically start with the new version when you relaunch it.

In case you need to do it manually, in RStudio, go to :Tools -> options -> General.

Check @micstr's answer for a more detailed walkthrough.

How to make an introduction page with Doxygen

Following syntax may help for adding a main page and related subpages for doxygen:

/*! \mainpage Drawing Shapes
 *
 * This project helps user to draw shapes.
 * Currently two types of shapes can be drawn:
 * - \subpage drawingRectanglePage "How to draw rectangle?"
 *
 * - \subpage drawingCirclePage "How to draw circle?"
 *
 */ 

/*! \page drawingRectanglePage How to draw rectangle?
 *
 * Lorem ipsum dolor sit amet
 *
 */

/*! \page drawingCirclePage How to draw circle?
 *
 * This page is about how to draw a circle.
 * Following sections describe circle:
 * - \ref groupCircleDefinition "Definition of Circle"
 * - \ref groupCircleClass "Circle Class"
 */

Creating groups as following also help for designing pages:

/** \defgroup groupCircleDefinition Circle Definition
 * A circle is a simple shape in Euclidean geometry.
 * It is the set of all points in a plane that are at a given distance from a given point, the centre;
 * equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
 * The distance between any of the points and the centre is called the radius.
 */

An example can be found here

Splitting words into letters in Java

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

Using intents to pass data between activities

In FirstActivity:

Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);

In SecondActivity

In onCreate()

String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");

How to list the properties of a JavaScript object?

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

Pass array to mvc Action via AJAX

I have had issues in the past when attempting to perform a POST (not sure if that is exactly what you are doing, but I recall when passing an array in, traditional must be set to true.

 var arrayOfValues = new Array();

 //Populate arrayOfValues 
 $.ajax({ 
      type: "POST",
      url: "<%= Url.Action("MyAction","Controller")%>",
      traditional: true,
      data: { 'arrayOfValues': arrayOfValues }              
 });

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

npm install private github repositories by dependency in package.json

There are multiple ways to do it as people point out, but the shortest versions are:

// from master
"depName": "user/repo",

// specific branch
"depName": "user/repo#branch",

// specific commit
"depName": "user/repo#commit",

// private repo
"depName": "git+https://[TOKEN]:[email protected]/user/repo.git"

e.g.

"dependencies" : {
  "hexo-renderer-marked": "amejiarosario/dsa.jsd#book",
  "hexo-renderer-marked": "amejiarosario/dsa.js#8ea61ce",
  "hexo-renderer-marked": "amejiarosario/dsa.js",
}

RESTful API methods; HEAD & OPTIONS

As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.2 OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.

If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).

If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.

A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".

The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

How do I lowercase a string in C?

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

Best way to repeat a character in C#

Extension methods:

public static string Repeat(this string s, int n)
{
    return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}

public static string Repeat(this char c, int n)
{
    return new String(c, n);
}

Replace comma with newline in sed on MacOS?

Apparently \r is the key!

$ sed 's/, /\r/g' file3.txt > file4.txt

Transformed this:

ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS

To this:

ABFS
AIRM
AMED
BOSC
CALI
ECPG
FRGI
GERN
GTIV
HSON
IQNT
JRCC
LTRE
MACK
MIDD
NKTR
NPSP
PME
PTIX
REFR
RSOL
UBNT
UPI
YONG
ZEUS

Downloading MySQL dump from command line

Note: This step only comes after dumping your MySQL file(which most of the answers above have addressed).

It assumes that you have the said dump file in your remote server and now you want to bring it down to your local computer.

To download the dumped .sql file from your remote server to your local computer, do

scp -i YOUR_SSH_KEY your_username@IP:name_of_file.sql ./my_local_project_dir

How to check Oracle database for long running queries

You can generate an AWR (automatic workload repository) report from the database.

Run from the SQL*Plus command line:

SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql

Read the document related to how to generate & understand an AWR report. It will give a complete view of database performance and resource issues. Once we are familiar with the AWR report it will be helpful to find Top SQL which is consuming resources.

Also, in the 12C EM Express UI we can generate an AWR.

How to convert seconds to HH:mm:ss in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:

_x000D_
_x000D_
const secs = 456;_x000D_
_x000D_
const formatted = moment.utc(secs*1000).format('HH:mm:ss');_x000D_
_x000D_
document.write(formatted);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

Check if all values in list are greater than a certain number

You can use all():

my_list1 = [30,34,56]
my_list2 = [29,500,43]
if all(i >= 30 for i in my_list1):
    print 'yes'
if all(i >= 30 for i in my_list2):
    print 'no'

Note that this includes all numbers equal to 30 or higher, not strictly above 30.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

Understanding SQL Server LOCKS on SELECT queries

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

Writing outputs to log file and console

I tried joonty's answer, but I also got the

exec: 1: not found

error. This is what works best for me (confirmed to work in zsh also):

#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError

The file /tmp/both.log afterwards contains

this is stdout
chmmm command not found 

The /tmp/both.log is appended unless you remove the -a from tee.

Hint: >(...) is a process substitution. It lets the exec to the tee command as if it were a file.

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Code for best fit straight line of a scatter plot in python

Assuming line of best fit for a set of points is:

y = a + b * x
where:
b = ( sum(xi * yi) - n * xbar * ybar ) / sum((xi - xbar)^2)
a = ybar - b * xbar

Code and plot

# sample points 
X = [0, 5, 10, 15, 20]
Y = [0, 7, 10, 13, 20]

# solve for a and b
def best_fit(X, Y):

    xbar = sum(X)/len(X)
    ybar = sum(Y)/len(Y)
    n = len(X) # or len(Y)

    numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
    denum = sum([xi**2 for xi in X]) - n * xbar**2

    b = numer / denum
    a = ybar - b * xbar

    print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))

    return a, b

# solution
a, b = best_fit(X, Y)
#best fit line:
#y = 0.80 + 0.92x

# plot points and fit line
import matplotlib.pyplot as plt
plt.scatter(X, Y)
yfit = [a + b * xi for xi in X]
plt.plot(X, yfit)

enter image description here

UPDATE:

notebook version

:not(:empty) CSS selector is not working?

input:not([value=""])

This works because we are selecting the input only when there isn't an empty string.

Create a custom View by inflating a layout?

Use the LayoutInflater as I shown below.

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Test-Path can be used with a special syntax:

Test-Path variable:global:foo

This also works for environment variables ($env:foo):

Test-Path env:foo

And for non-global variables (just $foo inline):

Test-Path variable:foo

In where shall I use isset() and !empty()

Using empty is enough:

if(!empty($variable)){
    // Do stuff
}

Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.

How to use paths in tsconfig.json?

You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Access denied for root user in MySQL command-line

Server file only change name folder

etc/mysql
rename
mysql-

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

Comparing two strings in C?

To answer the WHY in your question:

Because the equality operator can only be applied to simple variable types, such as floats, ints, or chars, and not to more sophisticated types, such as structures or arrays. To determine if two strings are equal, you must explicitly compare the two character strings character by character.

How to avoid the "Circular view path" exception with Spring MVC test

I solved this problem by using @ResponseBody like below:

@RequestMapping(value = "/resturl", method = RequestMethod.GET, produces = {"application/json"})
    @ResponseStatus(HttpStatus.OK)
    @Transactional(value = "jpaTransactionManager")
    public @ResponseBody List<DomainObject> findByResourceID(@PathParam("resourceID") String resourceID) {

Concatenate string with field value in MySQL

Here is a great answer to that:

SET sql_mode='PIPES_AS_CONCAT';

Find more here: https://stackoverflow.com/a/24777235/4120319

Here's the full SQL:

SET sql_mode='PIPES_AS_CONCAT';

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = 'category_id=' || tableOne.category_id;

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

This seemed to work for me on Max OSX: https://anaconda.org/menpo/opencv3

conda install -c menpo opencv3=3.1.0

I confirmed that you can import cv2 in python using python2.7 and python3

How to configure heroku application DNS to Godaddy Domain?

You can't use the naked domain of your-domain.com if it is not redirected to the www.your-domain.com. Heroku use the www.yourdomain.com which act here as a subdomain. So when you follow the default instruction to use your-domain.com then you will need to assign both of them.

We can actually assign only the naked domain without the www.your-domain.com. Use only your-domain.com when the domain's dns provider (NameServers) support ALIAS or ANAME for the @ Record to example.herokuapp.com without CNAME www.your-domain.com to it.

It will let you to point www.your-domain.com to other hosting separately (independent).

How to install the current version of Go in Ubuntu Precise

  1. Download say, go1.6beta1.linux-amd64.tar.gz from https://golang.org/dl/ into /tmp

wget https://storage.googleapis.com/golang/go1.6beta1.linux-amd64.tar.gz -o /tmp/go1.6beta1.linux-amd64.tar.gz

  1. un-tar into /usr/local/bin

sudo tar -zxvf go1.6beta1.linux-amd64.tar.gz -C /usr/local/bin/

  1. Set GOROOT, GOPATH, [on ubuntu add following to ~/.bashrc]

mkdir ~/go export GOPATH=~/go export PATH=$PATH:$GOPATH/bin export GOROOT=/usr/local/bin/go export PATH=$PATH:$GOROOT/bin

  1. Verify

go version should show be

go version go1.6beta1 linux/amd64

go env should show be

GOARCH="amd64" GOBIN="" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOOS="linux" GOPATH="/home/vats/go" GORACE="" GOROOT="/usr/local/bin/go" GOTOOLDIR="/usr/local/bin/go/pkg/tool/linux_amd64" GO15VENDOREXPERIMENT="1" CC="gcc" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0" CXX="g++" CGO_ENABLED="1"

What is the difference between .text, .value, and .value2?

target.Value will give you a Variant type

target.Value2 will give you a Variant type as well but a Date is coerced to a Double

target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

The safest thing to do is something like

Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2

And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

How to remove default chrome style for select Input?

Mixin for Less

.appearance (@value: none) {
    -webkit-appearance:     @value;
    -moz-appearance:        @value;
    -ms-appearance:         @value;
    -o-appearance:          @value;
    appearance:             @value;
}

How can I get customer details from an order in WooCommerce?

2017-2020 WooCommerce versions 3+ and CRUD Objects

1). You can use getter methods from WC_Order and WC_Abstract_Order classes on the WC_Order object instance like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Customer ID (User ID)
$customer_id = $order->get_customer_id(); // Or $order->get_user_id();

// Get the WP_User Object instance
$user = $order->get_user();

// Get the WP_User roles and capabilities
$user_roles = $user->roles;

// Get the Customer billing email
$billing_email  = $order->get_billing_email();

// Get the Customer billing phone
$billing_phone  = $order->get_billing_phone();

// Customer billing information details
$billing_first_name = $order->get_billing_first_name();
$billing_last_name  = $order->get_billing_last_name();
$billing_company    = $order->get_billing_company();
$billing_address_1  = $order->get_billing_address_1();
$billing_address_2  = $order->get_billing_address_2();
$billing_city       = $order->get_billing_city();
$billing_state      = $order->get_billing_state();
$billing_postcode   = $order->get_billing_postcode();
$billing_country    = $order->get_billing_country();

// Customer shipping information details
$shipping_first_name = $order->get_shipping_first_name();
$shipping_last_name  = $order->get_shipping_last_name();
$shipping_company    = $order->get_shipping_company();
$shipping_address_1  = $order->get_shipping_address_1();
$shipping_address_2  = $order->get_shipping_address_2();
$shipping_city       = $order->get_shipping_city();
$shipping_state      = $order->get_shipping_state();
$shipping_postcode   = $order->get_shipping_postcode();
$shipping_country    = $order->get_shipping_country();

2). You can also use the WC_Order get_data() method, to get an unprotected data array from Order meta data like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Order meta data in an unprotected array
$data  = $order->get_data(); // The Order data

$order_id        = $data['id'];
$order_parent_id = $data['parent_id'];

// Get the Customer ID (User ID)
$customer_id     = $data['customer_id'];

## BILLING INFORMATION:

$billing_email      = $data['billing']['email'];
$billing_phone      = $order_data['billing']['phone'];

$billing_first_name = $data['billing']['first_name'];
$billing_last_name  = $data['billing']['last_name'];
$billing_company    = $data['billing']['company'];
$billing_address_1  = $data['billing']['address_1'];
$billing_address_2  = $data['billing']['address_2'];
$billing_city       = $data['billing']['city'];
$billing_state      = $data['billing']['state'];
$billing_postcode   = $data['billing']['postcode'];
$billing_country    = $data['billing']['country'];

## SHIPPING INFORMATION:

$shipping_first_name = $data['shipping']['first_name'];
$shipping_last_name  = $data['shipping']['last_name'];
$shipping_company    = $data['shipping']['company'];
$shipping_address_1  = $data['shipping']['address_1'];
$shipping_address_2  = $data['shipping']['address_2'];
$shipping_city       = $data['shipping']['city'];
$shipping_state      = $data['shipping']['state'];
$shipping_postcode   = $data['shipping']['postcode'];
$shipping_country    = $data['shipping']['country'];

Now to get the user account data (from an Order ID):

1). You can use the methods from WC_Customer Class:

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get an instance of the WC_Customer Object from the user ID
$customer = new WC_Customer( $user_id );

$username     = $customer->get_username(); // Get username
$user_email   = $customer->get_email(); // Get account email
$first_name   = $customer->get_first_name();
$last_name    = $customer->get_last_name();
$display_name = $customer->get_display_name();

// Customer billing information details (from account)
$billing_first_name = $customer->get_billing_first_name();
$billing_last_name  = $customer->get_billing_last_name();
$billing_company    = $customer->get_billing_company();
$billing_address_1  = $customer->get_billing_address_1();
$billing_address_2  = $customer->get_billing_address_2();
$billing_city       = $customer->get_billing_city();
$billing_state      = $customer->get_billing_state();
$billing_postcode   = $customer->get_billing_postcode();
$billing_country    = $customer->get_billing_country();

// Customer shipping information details (from account)
$shipping_first_name = $customer->get_shipping_first_name();
$shipping_last_name  = $customer->get_shipping_last_name();
$shipping_company    = $customer->get_shipping_company();
$shipping_address_1  = $customer->get_shipping_address_1();
$shipping_address_2  = $customer->get_shipping_address_2();
$shipping_city       = $customer->get_shipping_city();
$shipping_state      = $customer->get_shipping_state();
$shipping_postcode   = $customer->get_shipping_postcode();
$shipping_country    = $customer->get_shipping_country();

2). The WP_User object (WordPress):

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get the WP_User instance Object
$user = new WP_User( $user_id );

$username     = $user->username; // Get username
$user_email   = $user->email; // Get account email
$first_name   = $user->first_name;
$last_name    = $user->last_name;
$display_name = $user->display_name;

// Customer billing information details (from account)
$billing_first_name = $user->billing_first_name;
$billing_last_name  = $user->billing_last_name;
$billing_company    = $user->billing_company;
$billing_address_1  = $user->billing_address_1;
$billing_address_2  = $user->billing_address_2;
$billing_city       = $user->billing_city;
$billing_state      = $user->billing_state;
$billing_postcode   = $user->billing_postcode;
$billing_country    = $user->billing_country;

// Customer shipping information details (from account)
$shipping_first_name = $user->shipping_first_name;
$shipping_last_name  = $user->shipping_last_name;
$shipping_company    = $user->shipping_company;
$shipping_address_1  = $user->shipping_address_1;
$shipping_address_2  = $user->shipping_address_2;
$shipping_city       = $user->shipping_city;
$shipping_state      = $user->shipping_state;
$shipping_postcode   = $user->shipping_postcode;
$shipping_country    = $user->shipping_country;

Related: How to get WooCommerce order details

Setting up an MS-Access DB for multi-user access

Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:

  1. No Locks
  2. All Records
  3. Edited Record

You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.

Transactions shouldn't be a problem if you use them correctly.

Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.

See other answers for Oracle comparison.

Delimiters in MySQL

You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/ 
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
    
    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;

I want to truncate a text or line with ellipsis using JavaScript

function truncate(string, length, delimiter) {
   delimiter = delimiter || "&hellip;";
   return string.length > length ? string.substr(0, length) + delimiter : string;
};

var long = "Very long text here and here",
    short = "Short";

truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"

(Mac) -bash: __git_ps1: command not found

High Sierra clean solution with colors !

No downloads. No brew. No Xcode

Just add it to your ~/.bashrc or ~/.bash_profile

export CLICOLOR=1
[ -f /Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh ] && . /Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh
export GIT_PS1_SHOWCOLORHINTS=1
export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWUPSTREAM="auto"
PROMPT_COMMAND='__git_ps1 "\h:\W \u" "\\\$ "'

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

Deserialize json object into dynamic object using Json.net

Yes it is possible. I have been doing that all the while.

dynamic Obj = JsonConvert.DeserializeObject(<your json string>);

It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:

ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.

T-SQL - function with default parameters

With user defined functions, you have to declare every parameter, even if they have a default value.

The following would execute successfully:

IF dbo.CheckIfSFExists( 23, default ) = 0
    SET @retValue = 'bla bla bla;

Image change every 30 seconds - loop

Just use That.Its Easy.

<script language="javascript" type="text/javascript">
     var images = new Array()
     images[0] = "img1.jpg";
     images[1] = "img2.jpg";
     images[2] = "img3.jpg";
     setInterval("changeImage()", 30000);
     var x=0;

     function changeImage()
     {
                document.getElementById("img").src=images[x]
                x++;
                if (images.length == x) 
                {
                    x = 0;
                }
     }
</script>

And in Body Write this Code:-

<img id="img" src="imgstart.jpg">

exception in thread 'main' java.lang.NoClassDefFoundError:

See http://scottizu.wordpress.com/2013/08/28/fixing-the-exception-in-thread-main-java-lang-noclassdeffounderror-in-eclipse/.

This is the long form of the Java commands that can be run from a Windows command prompt:

"C:\Program Files\Java\jdk1.6.0_18\bin\javac.exe" -classpath "C:\Users\Scott\workspace\myproject" com\mycompany\myapp\HelloWorld.java
"C:\Program Files\Java\jdk1.6.0_18\bin\java.exe" -classpath "C:\Users\Scott\workspace\myproject" com.mycompany.myapp.HelloWorld
  1. These commands can be run from any directory, meaning you don't have to be in the directory where your HelloWorld.java file is.
  2. The first line compiles your HelloWorld.java file, creating a HelloWorld.class file.
  3. The second line runs the HelloWorld.class file.
  4. The -classpath tells java where to look for the specified file in each command
  5. The Java compiler (javac.exe) expects the location of the java file, relative to the classpath (ie the file is located at C:\Users\Scott\workspace\myproject\com\mycompany\myapp\HelloWorld.java)
  6. Java (java.exe) expects the package (ie com.mycompany.myapp) and class (HelloWorld), relative to the classpath (ie the file is located at C:\Users\Scott\workspace\myproject\com\mycompany\myapp\HelloWorld.class)

Notice the classpath has no slash at the end. The javac.exe commands expects the file to end with ".java". The java.exe command expects the full class name and does not end with ".class".

There are a few ways to simplify these commands:

  1. You don't have to specify the entire path to java.exe. Add Java to the Windows Path (Run->sysdm.cpl->Advanced Tab->Environment Variables->Select Path->Edit->Append ";C:\Program Files\Java\jdk1.6.0_18\bin\"). Or you can append JAVA_HOME and create that Environment Variable.
  2. You don't have to enter the entire classpath (ie, you can just use -classpath "."). Enter the directory you will be working in:

    cd "C:\Users\Scott\workspace\myproject\"

  3. You can use the default package (put the HelloWorld.java file directory in your working directory and don't use the Java package directive)

If you make these changes you would run something like this (and you might be able to leave out -classpath "."):

cd "C:\Users\Scott\workspace\myproject\"
javac -classpath "." HelloWorld.java
java -classpath "." HelloWorld

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

https://www.google.com/search?g=[value from input-field]

But when you search with google, you notice the following URL:

https://www.google.nl/search?q=google+search+bar

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

ToString() function in Go

I prefer something like the following:

type StringRef []byte

func (s StringRef) String() string {
        return string(s[:])
}

…

// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

How to extract svg as file from web page

I don't know if this already been answered correctly or not. Well. Downloading the file from the source is not the resolution. How to grab *.svg from URL.

I installed 'svg-grabber' add-on to Google Chrome. That only partially resolve my problem, as Google Chrome does not have the shortcut to 'Back' one page.

I was trying to download the files from URL, but I kept getting an error, that there are no svg files on this page when I can see 40 of them. You can click on them, so they will open, but you cannot save it.

The folder within WordPress: .../static/img/icons/

I added 'Go Back With Backspace' add-on to Chrome, as I had to click on each file separately, as if they are white icons (that I am currently looking for), you will not see them. You have to click on the file. Then back. It was taking too long. Now is fine. There is a soft to download specific folder, but I do not want to download half of the internet, to just have get a white .

When you click on a white icon, a new tab opens, but it is all white. Then you click on svg-grabber icon in Chrome and it will open it in a new window on a black background with a button download all svg.

How do I install jmeter on a Mac?

jmeter is now just installed with

brew install jmeter

This version includes the plugin manager that you can use to download the additional plugins.

OUTDATED:

If you want to include the plugins (JMeterPlugins Standard, Extras, ExtrasLibs, WebDriver and Hadoop) use:

brew install jmeter --with-plugins

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

is there any PHP function for open page in new tab

This is a trick,

function OpenInNewTab(url) {

  var win = window.open(url, '_blank');
  win.focus();
}

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="OpenInNewTab();">Something To Click On</div>

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

There is a patch for Eclipse:
https://bugs.eclipse.org/bugs/attachment.cgi?id=262418&action=edit

Download this patch and put it to the plugins directory of your Eclipse installation. It will replace the default "org.eclipse.jst.server.tomcat.core_1.1.800.v201602282129.jar".

NOTE
After you add this patch you must choose "Apache Tomcat v9.0" when adding a server runtime environment in the Eclipse (Preferences > Server > Runtime Environments).
I.e. this patch allows you to select either Tomcat version 9.x or Tomcat version 8.5.x when adding Apache Tomcat v.9.0 runtime environment.


More details on can be found on the related bug report page: https://bugs.eclipse.org/bugs/show_bug.cgi?id=494936

Youtube - How to force 480p video quality in embed link / <iframe>

You can also use for 1080 hd values:

240p: &vq=small , 360p: &vq=medium , 480p: &vq=large , 720p: &vq=hd720 , &vq=hd1080

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

Integer division: How do you produce a double?

Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:

1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;

Note that casting the result won't do it. Because first division is done as per precedence rule.

double d = (double)(5 / 20); //produces 0.0

I do not think there is any problem with casting as such you are thinking about.

SQL Query to find the last day of the month

Select DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),DATEADD(MONTH, 1, GETDATE()))

This works great in T-sql ..

Replace the GETDATE() of the query with your column name .

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):

LDLIBS=-lm

This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o
    $(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@

Using generic std::function objects with member functions in one class

You can avoid std::bind doing this:

std::function<void(void)> f = [this]-> {Foo::doSomething();}

How to speed up insertion performance in PostgreSQL

See populate a database in the PostgreSQL manual, depesz's excellent-as-usual article on the topic, and this SO question.

(Note that this answer is about bulk-loading data into an existing DB or to create a new one. If you're interested DB restore performance with pg_restore or psql execution of pg_dump output, much of this doesn't apply since pg_dump and pg_restore already do things like creating triggers and indexes after it finishes a schema+data restore).

There's lots to be done. The ideal solution would be to import into an UNLOGGED table without indexes, then change it to logged and add the indexes. Unfortunately in PostgreSQL 9.4 there's no support for changing tables from UNLOGGED to logged. 9.5 adds ALTER TABLE ... SET LOGGED to permit you to do this.

If you can take your database offline for the bulk import, use pg_bulkload.

Otherwise:

  • Disable any triggers on the table

  • Drop indexes before starting the import, re-create them afterwards. (It takes much less time to build an index in one pass than it does to add the same data to it progressively, and the resulting index is much more compact).

  • If doing the import within a single transaction, it's safe to drop foreign key constraints, do the import, and re-create the constraints before committing. Do not do this if the import is split across multiple transactions as you might introduce invalid data.

  • If possible, use COPY instead of INSERTs

  • If you can't use COPY consider using multi-valued INSERTs if practical. You seem to be doing this already. Don't try to list too many values in a single VALUES though; those values have to fit in memory a couple of times over, so keep it to a few hundred per statement.

  • Batch your inserts into explicit transactions, doing hundreds of thousands or millions of inserts per transaction. There's no practical limit AFAIK, but batching will let you recover from an error by marking the start of each batch in your input data. Again, you seem to be doing this already.

  • Use synchronous_commit=off and a huge commit_delay to reduce fsync() costs. This won't help much if you've batched your work into big transactions, though.

  • INSERT or COPY in parallel from several connections. How many depends on your hardware's disk subsystem; as a rule of thumb, you want one connection per physical hard drive if using direct attached storage.

  • Set a high checkpoint_segments value and enable log_checkpoints. Look at the PostgreSQL logs and make sure it's not complaining about checkpoints occurring too frequently.

  • If and only if you don't mind losing your entire PostgreSQL cluster (your database and any others on the same cluster) to catastrophic corruption if the system crashes during the import, you can stop Pg, set fsync=off, start Pg, do your import, then (vitally) stop Pg and set fsync=on again. See WAL configuration. Do not do this if there is already any data you care about in any database on your PostgreSQL install. If you set fsync=off you can also set full_page_writes=off; again, just remember to turn it back on after your import to prevent database corruption and data loss. See non-durable settings in the Pg manual.

You should also look at tuning your system:

  • Use good quality SSDs for storage as much as possible. Good SSDs with reliable, power-protected write-back caches make commit rates incredibly faster. They're less beneficial when you follow the advice above - which reduces disk flushes / number of fsync()s - but can still be a big help. Do not use cheap SSDs without proper power-failure protection unless you don't care about keeping your data.

  • If you're using RAID 5 or RAID 6 for direct attached storage, stop now. Back your data up, restructure your RAID array to RAID 10, and try again. RAID 5/6 are hopeless for bulk write performance - though a good RAID controller with a big cache can help.

  • If you have the option of using a hardware RAID controller with a big battery-backed write-back cache this can really improve write performance for workloads with lots of commits. It doesn't help as much if you're using async commit with a commit_delay or if you're doing fewer big transactions during bulk loading.

  • If possible, store WAL (pg_xlog) on a separate disk / disk array. There's little point in using a separate filesystem on the same disk. People often choose to use a RAID1 pair for WAL. Again, this has more effect on systems with high commit rates, and it has little effect if you're using an unlogged table as the data load target.

You may also be interested in Optimise PostgreSQL for fast testing.

Hashmap does not work with int, char

Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try HashMap<Character, Integer> instead.

However, I'm having trouble figuring out why HashMap fails to be able to deal with primitive data types.

This is due to type erasure. Java didn't have generics from the beginning so a HashMap<Character, Integer> is really a HashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don't put the wrong type of value in or get the wrong type out, but at runtime there is only one HashMap class and it stores objects.

Other languages "specialize" types so in C++, a vector<bool> is very different from a vector<my_class> internally and they share no common vector<?> super-type. Java defines things though so that a List<T> is a List regardless of what T is for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.

Make an Android button change background on click through XML

Try:

public void onclick(View v){
            ImageView activity= (ImageView) findViewById(R.id.imageview1);
        button1.setImageResource(R.drawable.buttonpressed);}

How to declare and display a variable in Oracle

If using sqlplus you can define a variable thus:

define <varname>=<varvalue>

And you can display the value by:

define <varname>

And then use it in a query as, for example:

select *
from tab1
where col1 = '&varname';

Hiding user input on terminal in Linux script

for a solution that works without bash or certain features from read you can use stty to disable echo

stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig

How to set max and min value for Y axis

You have to overrride the scale, try this: (applies to ChartJS v1.x)

window.onload = function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {
        scaleOverride : true,
        scaleSteps : 10,
        scaleStepWidth : 50,
        scaleStartValue : 0 
    });
}

How do I automatically play a Youtube video (IFrame API) muted?

_x000D_
_x000D_
var video1;_x000D_
_x000D_
function onYouTubeIframeAPIReady(){_x000D_
 player = new YT.Player("video1", {_x000D_
  videoId: "id-number",_x000D_
  width: 300,_x000D_
  height: 200, _x000D_
  playerVars: {_x000D_
   "autoplay": 1, // and 0 means off_x000D_
   "controls": 1,_x000D_
   "showinfo": 0,_x000D_
   "modestbranding": 0,_x000D_
   "loop": 1,_x000D_
   "fs": 0,_x000D_
   "cc_load_policy": 0,_x000D_
   "iv_load_policy": 3,_x000D_
   },_x000D_
  events: {_x000D_
      'onReady': onPlayerReady_x000D_
  }_x000D_
 });_x000D_
  }_x000D_
_x000D_
function onPlayerReady(event) {_x000D_
    event.target.mute();_x000D_
    event.target.setVolume(0); //this can be set from 0 to 100_x000D_
}
_x000D_
_x000D_
_x000D_

Remember that the sound will not be muted in IE and Safari.

How to set the width of a RaisedButton in Flutter?

Wrap RaisedButton inside Container and give width to Container Widget.

e.g

 Container(
 width : 200,
 child : RaisedButton(
         child :YourWidget ,
         onPressed(){}
      ),
    )

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

When to use React "componentDidUpdate" method?

componentDidUpdate(prevProps){ 

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

How to read a file in other directory in python

For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

should actually be

x_file = open(os.path.join('direct', "5_1.txt"), "r")   

How to monitor Java memory usage?

There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.

Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.

Regex to match 2 digits, optional decimal, two digits

You mentioned that you want the regex to match each of those strings, yet you previously mention that the is 1-2 digits before the decimal?

This will match 1-2 digits followed by a possible decimal, followed by another 1-2 digits but FAIL on your example of .33

\d{1,2}\.?\d{1,2}

This will match 0-2 digits followed by a possible deciaml, followed by another 1-2 digits and match on your example of .33

\d{0,2}\.?\d{1,2}

Not sure exactly which one you're looking for.

How to set DialogFragment's width and height?

The dimension in outermost layout doesn't work in dialog. You can add a layout where set dimension below the outermost.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="xxdp"
    android:layout_height="xxdp"
    android:orientation="vertical">

</LinearLayout>