Programs & Examples On #Fuzzyfinder

FuzzyFinder is a plugin for VIM allowing quick file, buffer and command navigation.

Select mysql query between date?

Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:

This WILL include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'

This WON'T include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'

Failing to run jar file from command line: “no main manifest attribute”

If you are using Spring boot, you should add this plugin in your pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Android Device not recognized by adb

I recently had this issue (but before that debug over wifi was working fine) and since none of the above answers helped me let me share what I did.

  1. Go to developer options
  2. Find Select USB configurations and click it
  3. Choose MTP (Media Transfer Protocol)

Note: If it's set to this option chose another option such as PTP first then set it to MTP again.

UPDATE:

PTP stands for “Picture Transfer Protocol.” When Android uses this protocol, it appears to the computer as a digital camera.

MTP is actually based on PTP, but adds more features, or “extensions.” PTP works similarly to MTP and is commonly used by digital cameras.

AngularJS - value attribute for select

Try it as below:

var scope = $(this).scope();
alert(JSON.stringify(scope.model.options[$('#selOptions').val()].value));

How to use paths in tsconfig.json?

This can be set up on your tsconfig.json file, as it is a TS feature.

You can do like this:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environment/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
        ...

Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.

The character '@' is not mandatory.

After you set it up on that way, you can easily use it like this:

import { Yo } from '@config/index';

the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

How to set image to fit width of the page using jsPDF?

If you want a dynamic sized image to automatically fill the page as much as possible and still keep the image width/height-ratio, you could do as follows:

let width = doc.internal.pageSize.getWidth()
let height = doc.internal.pageSize.getHeight()

let widthRatio = width / canvas.width
let heightRatio = height / canvas.height

let ratio = widthRatio > heightRatio ? heightRatio : widthRatio

doc.addImage(
  canvas.toDataURL('image/jpeg', 1.0),
  'JPEG',
  0,
  0,
  canvas.width * ratio,
  canvas.height * ratio,
)

How do I put a variable inside a string?

I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

['file' + str(i) + '.pdf' for i in range(1,4)]

Really killing a process in Windows

One trick that works well is to attach a debugger and then quit the debugger.

On XP or Windows 2003 you can do this using ntsd that ships out of the box:

ntsd -pn myapp.exe

ntsd will open up a new window. Just type 'q' in the window to quit the debugger and take out the process.

I've known this to work even when task manager doesn't seem able to kill a process.

Unfortunately ntsd was removed from Vista and you have to install the (free) debbugging tools for windows to get a suitable debugger.

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Here is the perfect solution. You should use JQuery datepicker to user input date. It is very easy to use and it have lot of features that HTML input date don't have.

Click here to copy the JQuery datepicker code

Scrolling to element using webdriver?

You can scroll to the element by using javascript through the execute_javascript method. For example here is how I do it using SeleniumLibrary on Robot Framework:

web_element = self.selib.find_element(locator)
self.selib.execute_javascript(
    "ARGUMENTS",
    web_element,
    "JAVASCRIPT",
    'arguments[0].scrollIntoView({behavior: "instant", block: "start", inline: "start"});'
)

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

explode string in jquery

Try This

var data = 'allow~5'; 
var result=data.split('~');

RESULT

alert(result[0]);

How to implement and do OCR in a C# project?

Some online API's work pretty well: ocr.space and Google Cloud Vision. Both of these are free, as long as you do less than 1000 OCR's per month. You can drag & drop an image to do a quick manual test to see how they perform for your images.

I find OCR.space easier to use (no messing around with nuget libraries), but, for my purpose, Google Cloud Vision provided slightly better results than OCR.space.

Google Cloud Vision example:

GoogleCredential cred = GoogleCredential.FromJson(json);
Channel channel = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host, ImageAnnotatorClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
Image image = Image.FromStream(stream);

EntityAnnotation googleOcrText = client.DetectText(image).First();
Console.Write(googleOcrText.Description);

OCR.space example:

string uri = $"https://api.ocr.space/parse/imageurl?apikey=helloworld&url={imageUri}";
string responseString = WebUtilities.DoGetRequest(uri);
OcrSpaceResult result = JsonConvert.DeserializeObject<OcrSpaceResult>(responseString);
if ((!result.IsErroredOnProcessing) && !String.IsNullOrEmpty(result.ParsedResults[0].ParsedText))
  return result.ParsedResults[0].ParsedText;

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

Compare and contrast REST and SOAP web services?

In day to day, practical programming terms, the biggest difference is in the fact that with SOAP you are working with static and strongly defined data exchange formats where as with REST and JSON data exchange formatting is very loose by comparison. For example with SOAP you can validate that exchanged data matches an XSD schema. The XSD therefore serves as a 'contract' on how the client and the server are to understand how the data being exchanged must be structured.

JSON data is typically not passed around according to a strongly defined format (unless you're using a framework that supports it .. e.g. http://msdn.microsoft.com/en-us/library/jj870778.aspx or implementing json-schema).

In-fact, some (many/most) would argue that the "dynamic" secret sauce of JSON goes against the philosophy/culture of constraining it by data contracts (Should JSON RESTful web services use data contract)

People used to working in dynamic loosely typed languages tend to feel more comfortable with the looseness of JSON while developers from strongly typed languages prefer XML.

http://www.mnot.net/blog/2012/04/13/json_or_xml_just_decide

form_for but to post to a different action

form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')

or

form_for @user, :url => whatever_path

LOAD DATA INFILE Error Code : 13

CentOS 7+ Minimal Secure Solution: (should work with RedHat too)

chcon -Rv --type=mysqld_db_t /YOUR/PATH/

Explanation:

Knowing that you applied the good practice of using secure-file-priv=/YOUR/PATH/ in my.cnf in order to use load data infile sql statement, you still see the following:

ERROR 13 (HY000): Can't get stat of '/YOUR/PATH/FILE.EXT' (Errcode: 13 "Permission denied")

That's caused by SELinux Enforcing mode, it's not secure to change the mode to Permissive or disable SELinux.
In short,

chcon change SELinux security context of a file or files/directories in a similar way to how 'chown' or 'chmod' may be used to change the ownership or standard file permissions of a file.

SELinux Enforcing mode prevents mysqld from accessing directories with secure-context-type default_t, hence we need to change the secure-context-type of our path to mysqld_db_t. To see the current secure-context-type use the command:

ls --directory --scontext /YOUR/PATH/

In case you want to reset/undo the solution, then apply below command:

restorecon -Rv /YOUR/PATH/

The solution I shared is referenced in below links:

https://wiki.centos.org/HowTos/SELinux
https://mariadb.com/kb/en/selinux/
https://linux.die.net/man/8/mysqld_selinux

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

I am working behind a proxy and just installed SASS by downloading directly from http://rubygems.org.

I then ran sudo gem install [path/to/downloaded/gem/file]. I cannot say this will work for all gems, but it may help some people.

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

Correct way to quit a Qt program?

While searching this very question I discovered this example in the documentation.

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);

Mutatis mutandis for your particular action of course.

Along with this note.

It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()

Making a button invisible by clicking another button in HTML

Using jQuery!

var demoShow = function(){
    $("#p2").hide();
}

But I would recommend you give an id to your button on which you want an action to happen. For example:

<input type="button" id="p1" value="edit" />
<input type="button" id="p2" value="submit" name="submit" />

<script type="text/javascript"> 
$("#p1").click(function(){
    $("#p2").hide();
});
</script>

To show it again you can simply write: $("#p2").show();

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

Forget setAttribute(): it's badly broken and doesn't always do what you might expect in old IE (IE <= 8 and compatibility modes in later versions). Use the element's properties instead. This is generally a good idea, not just for this particular case. Replace your code with the following, which will work in all major browsers:

var hiddenInput = document.createElement("input");
hiddenInput.id = "uniqueIdentifier";
hiddenInput.type = "hidden";                     
hiddenInput.value = ID;
hiddenInput.className = "ListItem";

Update

The nasty hack in the second code block in the question is unnecessary, and the code above works fine in all major browsers, including IE 6. See http://www.jsfiddle.net/timdown/aEvUT/. The reason why you get null in your alert() is that when it is called, the new input is not yet in the document, hence the document.getElementById() call cannot find it.

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Best way to combine two or more byte arrays in C#

Here's a generalization of the answer provided by @Jon Skeet. It is basically the same, only it is usable for any type of array, not only bytes:

public static T[] Combine<T>(T[] first, T[] second)
{
    T[] ret = new T[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

public static T[] Combine<T>(T[] first, T[] second, T[] third)
{
    T[] ret = new T[first.Length + second.Length + third.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
                     third.Length);
    return ret;
}

public static T[] Combine<T>(params T[][] arrays)
{
    T[] ret = new T[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (T[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
}

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

textarea's rows, and cols attribute in CSS

I just wanted to post a demo using calc() for setting rows/height, since no one did.

_x000D_
_x000D_
body {_x000D_
  /* page default */_x000D_
  font-size: 15px;_x000D_
  line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
  /* demo related */_x000D_
  width: 300px;_x000D_
  margin-bottom: 1em;_x000D_
  display: block;_x000D_
  _x000D_
  /* rows related */_x000D_
  font-size: inherit;_x000D_
  line-height: inherit;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows); */_x000D_
  height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
  height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
_x000D_
_x000D_

If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.

How can I pad a String in Java?

Here is another way to pad to the right:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";

How to stop C# console applications from closing automatically?

Use:

Console.ReadKey();

For it to close when someone presses any key, or:

Console.ReadLine();

For when the user types something and presses enter.

Find Facebook user (url to profile page) by known email address

Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com

You can use Person Api there and get the info.

This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********

Also there is xml or json choice.

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

Formatting text in a TextBlock

a good site, with good explanations:

http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF

Edit

There are different methods to format the text. for a basic formatting (the easiest in my opinion):

    <TextBlock Margin="10" TextWrapping="Wrap">
                    TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
    </TextBlock>

Example 1 shows basic formatting with Bold Itallic and underscored text.

Following includes the SPAN method, with this you van highlight text:

   <TextBlock Margin="10" TextWrapping="Wrap">
                    This <Span FontWeight="Bold">is</Span> a
                    <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                    with <Span TextDecorations="Underline">several</Span>
                    <Span FontStyle="Italic">Span</Span> elements,
                    <Span Foreground="Blue">
                            using a <Bold>variety</Bold> of <Italic>styles</Italic>
                    </Span>.
   </TextBlock>

Example 2 shows the span function and the different possibilities with it.

For a detailed explanation check the site!

Examples

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

In my case, I just had to make sure I have my urls both with and without www for Application Domain and Redirect URLs:

enter image description here

In my case, I had to use: signin-facebook after my site url, for redirect url.

Resize Google Maps marker icon image

Delete origin and anchor will be more regular picture

  var icon = {
        url: "image path", // url
        scaledSize: new google.maps.Size(50, 50), // size
    };

 marker = new google.maps.Marker({
  position: new google.maps.LatLng(lat, long),
  map: map,
  icon: icon
 });

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

logger configuration to log to file and print to stdout

Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).

import logging
logging.getLogger().addHandler(logging.StreamHandler())

If you want to output to stdout instead of stderr, you just need to specify it to the StreamHandler constructor.

import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))

You could also add a Formatter to it so all your log lines have a common header.

ie:

import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

Prints to the format of:

2012-12-05 16:58:26,618 [MainThread  ] [INFO ]  my message

Which one is the best PDF-API for PHP?

From the mpdf site: "mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements."

mpdf is superior to FPDF for language handling and UTF-8 support. For CJK support it not only supports font embedding, but font subsetting (so your CJK PDFs are not oversized). TCPDF and FPDF have nothing on the UTF-8 and Font support of mpdf. It even comes with some open source fonts as of version 5.0.

How do you dismiss the keyboard when editing a UITextField

Programmatically set the delegate of the UITextField in swift 3

Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )

 lazy var firstNameTF: UITextField = {

    let firstname = UITextField()
    firstname.placeholder = "FirstName"
    firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    firstname.textAlignment = .center
    firstname.borderStyle = UITextBorderStyle.roundedRect
    firstname.keyboardType = UIKeyboardType.default
    firstname.delegate = self
    return firstname
}()

lazy var lastNameTF: UITextField = {

    let lastname = UITextField()
    lastname.placeholder = "LastName"
    lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)
    lastname.textAlignment = .center
    lastname.borderStyle = UITextBorderStyle.roundedRect
    lastname.keyboardType = UIKeyboardType.default
    lastname.delegate = self
    return lastname
}()

lazy var emailIdTF: UITextField = {

    let emailid = UITextField()
    emailid.placeholder = "EmailId"
    emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)
    emailid.textAlignment = .center
    emailid.borderStyle = UITextBorderStyle.roundedRect
    emailid.keyboardType = UIKeyboardType.default
    emailid.delegate = self
    return emailid
}()

// Mark:- handling delegate textField..

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == firstNameTF {

        lastNameTF.becomeFirstResponder()
    }

    else if textField == lastNameTF {

        emailIdTF.becomeFirstResponder()
    }
    else {
        view.emailIdTF(true)
    }
    return true
}

Is it possible in Java to catch two exceptions in the same catch block?

Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:

 try {
  // some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
   throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.

Permanently add a directory to PYTHONPATH?

On MacOS, Instead of giving path to a specific library. Giving full path to the root project folder in

~/.bash_profile 

made my day, for example:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

after this do:

source ~/.bash_profile

Understanding Popen.communicate

.communicate() writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.

The exception EOFError is raised in the child process by raw_input() (it expected data but got EOF (no data)).

p.stdout.read() hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()) that causes a deadlock.

To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:

from subprocess import PIPE, Popen

p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
    print >>p.stdin, i # write input
    p.stdin.flush() # not necessary in this case
    print p.stdout.readline(), # read output

print p.communicate("n\n")[0], # signal the child to exit,
                               # read the rest of the output, 
                               # wait for the child to exit

Note: it is a very fragile code if read/write are not in sync; it deadlocks.

Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).

bufsize=1 makes the pipes line-buffered on the parent side.

How to embed small icon in UILabel

Swift 4 UIlabel Extension to add Image to Label with reference to above answers

extension UILabel {
  func set(image: UIImage, with text: String) {
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    let attachmentStr = NSAttributedString(attachment: attachment)

    let mutableAttributedString = NSMutableAttributedString()
    mutableAttributedString.append(attachmentStr)

    let textString = NSAttributedString(string: text, attributes: [.font: self.font])
    mutableAttributedString.append(textString)

    self.attributedText = mutableAttributedString
  }
}

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

Reverting to a previous revision using TortoiseSVN

There are several ways to do that. But do not just update to the earlier revision as suggested here.

The easiest way to revert the changes from a single revision, or from a range of revisions, is to use the revision log dialog. This is also the method to use of you want to discard recent changes and make an earlier revision the new HEAD.

  1. Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.
  2. Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.
  3. Select the revision you wish to revert. If you want to undo a range of revisions, select the first one and hold Shift while selecting the last one. Note that for multiple revisions, the range must be unbroken with no gaps. Right click on the selected revision(s), then select Context Menu ? Revert changes from this revision.
  4. Or if you want to make an earlier revision the new HEAD revision, right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.

You have reverted the changes within your working copy. Check the results, then commit the changes.

All solutions are explained in the "How Do I..." part of the TortoiseSVN docs.

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

Checking if an Android application is running in the background

To piggyback on what CommonsWare and Key have said, you could perhaps extend the Application class and have all of your activities call that on their onPause/onResume methods. This would allow you to know which Activity(ies) are visible, but this could probably be handled better.

Can you elaborate on what you have in mind exactly? When you say running in the background do you mean simply having your application still in memory even though it is not currently on screen? Have you looked into using Services as a more persistent way to manage your app when it is not in focus?

What is the best/simplest way to read in an XML file in Java application?

Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.

JavaScript Loading Screen while page loads

I would suggest adding class no-js to your html to nest your CSS selectors under it like:

.loading {
    display: none;
 }

.no-js .loading {
 display: block;
 //....
}

and when you finish loading your credit code remove it:

$('html').removeClass('no-js');

This will hide your loading spinner as there's no no-js class in html it means you already loaded your credit code

How do I capture SIGINT in Python?

From Python's documentation:

import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10) # Press Ctrl+c here

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

Using ping in c#

private void button26_Click(object sender, EventArgs e)
{
    System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
    proc.FileName = @"C:\windows\system32\cmd.exe";
    proc.Arguments = "/c ping -t " + tx1.Text + " ";
    System.Diagnostics.Process.Start(proc);
    tx1.Focus();
}

private void button27_Click(object sender, EventArgs e)
{
    System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
    proc.FileName = @"C:\windows\system32\cmd.exe";
    proc.Arguments = "/c ping  " + tx2.Text + " ";
    System.Diagnostics.Process.Start(proc);
    tx2.Focus();
}

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

Best way to integrate Python and JavaScript?

There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete: http://code.google.com/p/pyjscore/

Task.Run with Parameter(s)?

I know this is an old thread, but I wanted to share a solution I ended up having to use since the accepted post still has an issue.

The Issue:

As pointed out by Alexandre Severino, if param (in the function below) changes shortly after the function call, you might get some unexpected behavior in MethodWithParameter.

Task.Run(() => MethodWithParameter(param)); 

My Solution:

To account for this, I ended up writing something more like the following line of code:

(new Func<T, Task>(async (p) => await Task.Run(() => MethodWithParam(p)))).Invoke(param);

This allowed me to safely use the parameter asynchronously despite the fact that the parameter changed very quickly after starting the task (which caused issues with the posted solution).

Using this approach, param (value type) gets its value passed in, so even if the async method runs after param changes, p will have whatever value param had when this line of code ran.

Hadoop cluster setup - java.net.ConnectException: Connection refused

I had the similar prolem with OP. As the terminal output suggested, I went to http://wiki.apache.org/hadoop/ConnectionRefused

I tried to change my /etc/hosts file as suggested here, i.e. remove 127.0.1.1 as OP suggested it will create another error.

So in the end, I leave it as is. The following is my /etc/hosts

127.0.0.1       localhost.localdomain   localhost
127.0.1.1       linux
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

In the end, I found that my namenode did not started correctly, i.e. When you type sudo netstat -lpten | grep java in the terminal, there will not be any JVM process running(listening) on port 9000.

So I made two directories for namenode and datanode respectively(if you have not done so). You don't have to put where I put it, please replace it based on your hadoop directory. i.e.

mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/namenode
mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/datanode

I reconfigured my hdfs-site.xml.

<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
   <property>
        <name>dfs.namenode.name.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/namenode</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/datanode</value>
    </property>
</configuration>

In terminal, stop your hdfs and yarn with script stop-dfs.sh and stop-yarn.sh. They are located in your hadoop directory/sbin. In my case, it's /home/hadoopuser/hadoop-2.6.2/sbin/.

Then start your hdfs and yarn with script start-dfs.sh and start-yarn.sh After it is started, type jps in your terminal to see if your JVM processes are running correctly. It should show the following.

15678 NodeManager
14982 NameNode
15347 SecondaryNameNode
23814 Jps
15119 DataNode
15548 ResourceManager

Then try to use netstat again to see if your namenode is listening to port 9000

sudo netstat -lpten | grep java

If you successfully set up the namenode, you should see the following in your terminal output.

tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 1001 175157 14982/java

Then try to type the command hdfs dfs -mkdir /user/hadoopuser If this command executes sucessfully, now you can list your directory in the HDFS user directory by hdfs dfs -ls /user

Regex pattern including all special characters

If you only rely on ASCII characters, you can rely on using the hex ranges on the ASCII table. Here is a regex that will grab all special characters in the range of 33-47, 58-64, 91-96, 123-126

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]

However you can think of special characters as not normal characters. If we take that approach, you can simply do this

^[A-Za-z0-9\s]+

Hower this will not catch _ ^ and probably others.

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Bootstrap: Open Another Modal in Modal

To open another modal window in a current opened modal window,
you can use bootstrap-modal

bootstrap-modal DEMO

Sample settings.xml

The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml with you since these settings are user specific.

If you need to configure a proxy, have a look at the section about Proxies.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.somewhere.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts>
    </proxy>
  </proxies>
  ...
</settings>
  • id: The unique identifier for this proxy. This is used to differentiate between proxy elements.
  • active: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.
  • protocol, host, port: The protocol://host:port of the proxy, seperated into discrete elements.
  • username, password: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.
  • nonProxyHosts: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common

Difference between acceptance test and functional test?

The difference is between testing the problem and the solution. Software is a solution to a problem, both can be tested.

The functional test confirms the software performs a function within the boundaries of how you've solved the problem. This is an integral part of developing software, comparable to the testing that is done on mass produced product before it leaves the factory. A functional test verifies that the product actually works as you (the developer) think it does.

Acceptance tests verify the product actually solves the problem it was made to solve. This can best be done by the user (customer), for instance performing his/her tasks that the software assists with. If the software passes this real world test, it's accepted to replace the previous solution. This acceptance test can sometimes only be done properly in production, especially if you have anonymous customers (e.g. a website). Thus a new feature will only be accepted after days or weeks of use.

Functional testing - test the product, verifying that it has the qualities you've designed or build (functions, speed, errors, consistency, etc.)

Acceptance testing - test the product in its context, this requires (simulation of) human interaction, test it has the desired effect on the original problem(s).

How to set a cell to NaN in a pandas dataframe

As of pandas 1.0.0, you no longer need to use numpy to create null values in your dataframe. Instead you can just use pandas.NA (which is of type pandas._libs.missing.NAType), so it will be treated as null within the dataframe but will not be null outside dataframe context.

Android: java.lang.SecurityException: Permission Denial: start Intent

I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.

It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.

here is the documentation http://developer.android.com/guide/topics/manifest/activity-element.html#exported

tl;dr: addandroid:exported="true" to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)

Simple WPF RadioButton Binding?

This example might be seem a bit lengthy, but its intention should be quite clear.

It uses 3 Boolean properties in the ViewModel called, FlagForValue1, FlagForValue2 and FlagForValue3. Each of these 3 properties is backed by a single private field called _intValue.

The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1 bool property in the view model and the other two accordingly.

When setting one of the properties in the view model (e.g. FlagForValue1), its important to also raise property changed events for the other two properties (e.g. FlagForValue2, and FlagForValue3) so the UI (WPF INotifyPropertyChanged infrastructure) can selected / deselect each radio button correctly.

    private int _intValue;

    public bool FlagForValue1
    {
        get
        {
            return (_intValue == 1) ? true : false;
        }
        set
        {
            _intValue = 1;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue2
    {
        get
        {
            return (_intValue == 2) ? true : false;
        }
        set
        {
            _intValue = 2;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

    public bool FlagForValue3
    {
        get
        {
            return (_intValue == 3) ? true : false;
        }
        set
        {
            _intValue = 3;
            RaisePropertyChanged("FlagForValue1");
            RaisePropertyChanged("FlagForValue2");
            RaisePropertyChanged("FlagForValue3");
        }
    }

The xaml looks like this:

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
                             >Value 1</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
                             >Value 2</RadioButton>

                <RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
                             >Value 3</RadioButton>

Can I hide/show asp:Menu items based on role?

To find menu items in content page base on roles

 protected void Page_Load(object sender, EventArgs e)
{
   if (Session["AdminSuccess"] != null)
        {
           Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");

    //you must know the index of items to be removed first
    mainMenu.Items.RemoveAt(1);

    //or you try to hide menu and list items inside menu with css 
    // cssclass must be defined in style tag in .aspx page
    mainMenu.CssClass = ".hide";

        }   

}

<style type="text/css">
.hide
    {
        visibility: hidden;
     }
  </style>  

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

Best way of invoking getter by reflection

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

Although Tomcat does forcibly deregister the JDBC driver for you, it is nonetheless good practice to clean up all resources created by your webapp on context destruction in case you move to another servlet container which doesn't do the memory leak prevention checks that Tomcat does.

However, the methodology of blanket driver deregistration is dangerous. Some drivers returned by the DriverManager.getDrivers() method may have been loaded by the parent ClassLoader (i.e., the servlet container's classloader) not the webapp context's ClassLoader (e.g., they may be in the container's lib folder, not the webapp's, and therefore shared across the whole container). Deregistering these will affect any other webapps which may be using them (or even the container itself).

Therefore, one should check that the ClassLoader for each driver is the webapp's ClassLoader before deregistering it. So, in your ContextListener's contextDestroyed() method:

public final void contextDestroyed(ServletContextEvent sce) {
    // ... First close any background tasks which may be using the DB ...
    // ... Then close any DB connection pools ...

    // Now deregister JDBC drivers in this context's ClassLoader:
    // Get the webapp's ClassLoader
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    // Loop through all drivers
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        if (driver.getClass().getClassLoader() == cl) {
            // This driver was registered by the webapp's ClassLoader, so deregister it:
            try {
                log.info("Deregistering JDBC driver {}", driver);
                DriverManager.deregisterDriver(driver);
            } catch (SQLException ex) {
                log.error("Error deregistering JDBC driver {}", driver, ex);
            }
        } else {
            // driver was not registered by the webapp's ClassLoader and may be in use elsewhere
            log.trace("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader", driver);
        }
    }
}

Pointer arithmetic for void pointer in C

The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

C11 standard §6.2.5

Paragraph - 19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Following program is working fine in GCC compiler.

#include<stdio.h>

int main()
{
    int arr[2] = {1, 2};
    void *ptr = &arr;
    ptr = ptr + sizeof(int);
    printf("%d\n", *(int *)ptr);
    return 0;
}

May be other compilers generate an error.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I like these methods for dealing with enums that have the Flags attribute set:

public static bool AnyOf(this object mask, object flags)
{
    return ((int)mask & (int)flags) != 0;
}
public static bool AllOf(this object mask, object flags)
{
    return ((int)mask & (int)flags) == (int)flags;
}
public static object SetOn(this object mask, object flags)
{
    return (int)mask | (int)flags;
}
etc.

Example usage:

var options = SomeOptions.OptionA;
options = options.SetOn(OptionB);
options = options.SetOn(OptionC);

if (options.AnyOf(SomeOptions.OptionA | SomeOptions.OptionB))
{
etc.

The original methods were from this article: http://www.codeproject.com/KB/cs/masksandflags.aspx?display=Print I just converted them to extension methods.

The one problem with them though is that the parameters of object type, which means that all objects end up being extended with these methods, whereas ideally they should only apply to enums.

Update As per the comments, you can get around the "signature pollution", at the expense of performance, like this:

public static bool AnyOf(this Enum mask, object flags)
{
    return (Convert.ToInt642(mask) & (int)flags) != 0;
}

How do I register a .NET DLL file in the GAC?

As ando said, just drag and drop the assembly to the C:\windows\assembly folder. It works.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Determine version of Entity Framework I am using?

can check it in packages.config file.

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages> 

Check if all checkboxes are selected

$('.abc[checked!=true]').length == 0

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

JQuery get all elements by class name

One possible way is to use .map() method:

var all = $(".mbox").map(function() {
    return this.innerHTML;
}).get();

console.log(all.join());

DEMO: http://jsfiddle.net/Y4bHh/

N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

How to remove \n from a list element?

I had this issue and solved it using the chomp function described above:

def chomp(s):
    return s[:-1] if s.endswith('\n') else s

def trim_newlines(slist):
    for i in range(len(slist)):
        slist[i] = chomp(slist[i])
    return slist
.....
names = theFile.readlines()
names = trim_newlines(names)
....

Pretty-print an entire Pandas Series / DataFrame

Try this

pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Browse for a directory in C#

Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.

How to pass a variable to the SelectCommand of a SqlDataSource?

Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.

In the code behind, add:

Dim MyVariable as Long


ReadOnly Property MyCustomProperty As Long
    Get
        Return MyVariable
    End Get
End Property

In the select parameters section add:

<asp:ControlParameter ControlID="__Page" Name="MyParameter" 
PropertyName="MyCustomProperty" Type="Int32" />

Adding hours to JavaScript Date object?

It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.

Date.prototype.addHours= function(h){
    var copiedDate = new Date(this.getTime());
    copiedDate.setHours(copiedDate.getHours()+h);
    return copiedDate;
}

This way you can chain a bunch of method calls without worrying about state.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

Removing duplicates from a list of lists

a_list = [
          [1,2],
          [1,2],
          [2,3],
          [3,4]
]

print (list(map(list,set(map(tuple,a_list)))))

outputs: [[1, 2], [3, 4], [2, 3]]

What is char ** in C?

Technically, the char* is not an array, but a pointer to a char.

Similarly, char** is a pointer to a char*. Making it a pointer to a pointer to a char.

C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of chars, or an array of strings.

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Well if you know the order of your words.. you can use:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'

Also you can use:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'

Android Recyclerview GridLayoutManager column spacing

There is only one easy solution, that you can remember and implement wherever needed. No bugs, no crazy calculations. Put margin to the card / item layout and put the same size as padding to the RecyclerView:

item_layout.xml

<CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:margin="10dp">

activity_layout.xml

<RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"/>

UPDATE: enter image description here

Euclidean distance of two vectors

As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

How to load GIF image in Swift?

Load GIF image Swift :

## Reference.

#1 : Copy the swift file from This Link :

#2 : Load GIF image Using Name

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)

#3 : Load GIF image Using Data

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)

#4 : Load GIF image Using URL

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)

Download Demo Code

OUTPUT :

iPhone 8 / iOS 11 / xCode 9

enter image description here

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

Disable vertical sync for glxgears

Disabling the Sync to VBlank checkbox in nvidia-settings (OpenGL Settings tab) does the trick for me.

How do I compare two columns for equality in SQL Server?

A solution avoiding CASE WHEN is to use COALESCE.

SELECT
    t1.Col2 AS t1Col2,
    t2.Col2 AS t2Col2,
    COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
 FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID

NULL_IF_SAME column will give NULL for all rows where t1.col2 = t2.col2 (including NULL). Though this is not more readable than CASE WHEN expression, it is ANSI SQL.

Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):

1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.

Now if you have one of the numeric data types and want bits, in the above LEN function converts to string first which may be problematic,so instead this should work:

1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC

Above will work for Integers without CAST.

NOTE: also in SQLServer 2012, we have IIF function.

Store query result in a variable using in PL/pgSQL

You can use the following example to store a query result in a variable using PL/pgSQL:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

How do I bind to list of checkbox values with AngularJS?

The following solution seems like a good option,

<label ng-repeat="fruit in fruits">
  <input
    type="checkbox"
    ng-model="fruit.checked"
    ng-value="true"
  > {{fruit.fruitName}}
</label>

And in controller model value fruits will be like this

$scope.fruits = [
  {
    "name": "apple",
    "checked": true
  },
  {
    "name": "orange"
  },
  {
    "name": "grapes",
    "checked": true
  }
];

Swift alert view with OK and Cancel: which button tapped?

You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.

UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.

github to see the details

example:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

Passing command line arguments to R CMD BATCH

In your R script, called test.R:

args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")

From the command line run:

R CMD BATCH -4 test.R

Your output file, test.Rout, will show that the argument 4 has been successfully passed to R:

cat test.Rout

> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user  system elapsed 
0.222   0.022   0.236 

GoTo Next Iteration in For Loop in java

As mentioned in all other answers, the keyword continue will skip to the end of the current iteration.

Additionally you can label your loop starts and then use continue [labelname]; or break [labelname]; to control what's going on in nested loops:

loop1: for (int i = 1; i < 10; i++) {
    loop2: for (int j = 1; j < 10; j++) {
        if (i + j == 10)
            continue loop1;

        System.out.print(j);
    }
    System.out.println();
}

Adding additional data to select options using jQuery

HTML

<Select id="SDistrict" class="form-control">
    <option value="1" data-color="yellow" > Mango </option>
</select>

JS when initialized

   $('#SDistrict').selectize({
        create: false,
        sortField: 'text',
        onInitialize: function() {
            var s = this;
            this.revertSettings.$children.each(function() {
                $.extend(s.options[this.value], $(this).data());
            });
        },
        onChange: function(value) {
            var option = this.options[value];
            alert(option.text + ' color is ' + option.color);
        }
    });

You can access data attribute of option tag with option.[data-attribute]

JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/

How to style a div to be a responsive square?

Works on almost all browsers.

You can try giving padding-bottom as a percentage.

<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>

The outer div is making a square and inner div contains the content. This solution worked for me many times.

Here's a jsfiddle

How to read line by line of a text area HTML tag

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Simple and easy:

$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

Why is document.write considered a "bad practice"?

It breaks pages using XML rendering (like XHTML pages).

Best: some browser switch back to HTML rendering and everything works fine.

Probable: some browser disable the document.write() function in XML rendering mode.

Worst: some browser will fire an XML error whenever using the document.write() function.

Conversion failed when converting the varchar value to data type int in sql

The line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

is wrong.

@Prefix is 'J' and LEN(...anything...) is an int, hence the type mismatch.


It seems to me, you actually want to do,

SELECT
        @maxCode = MAX(
            CAST(SUBSTRING(
                Voucher_No,
                @startFrom + 1,
                LEN(Voucher_No) - (@startFrom + 1)) AS INT)
    FROM
        dbo.Journal_Entry;

SELECT  @Prefix + CAST(@maxCode AS VARCHAR(10));

but, I couldn't say. If you illustrated before and after data, it would help.

Get started with Latex on Linux

I would recommend start using Lyx, with that you can use Latex just as easy as OOO-Writer. It gives you the possibility to step into Latex deeper by manually adding Latex-Code to your Document. PDF is just one klick away after installatioin. Lyx is cross-plattform.

How do I preserve line breaks when getting text from a textarea?

Similar questions are here

detect line breaks in a text area input

detect line break in textarea

You can try this:

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
document.getElementById('output').innerHTML = textContent.replace(/\n/g, '<br/>');_x000D_
  _x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10 >This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again</textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
_x000D_
<p id='output'></p>
_x000D_
_x000D_
_x000D_

document.querySelector('textarea').value; will get the text content of the textarea and textContent.replace(/\n/g, '<br/>') will find all the newline character in the source code /\n/g in the content and replace it with the html line-break <br/>.


Another option is to use the html <pre> tag. See the demo below

_x000D_
_x000D_
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
_x000D_
  var content = '<pre>';_x000D_
  _x000D_
  var textContent = document.querySelector('textarea').value;_x000D_
  _x000D_
  content += textContent;_x000D_
  _x000D_
  content += '</pre>';_x000D_
_x000D_
  document.getElementById('output').innerHTML = content;_x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10>This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again </textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
<div id='output'> </div>
_x000D_
_x000D_
_x000D_

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

Is it possible to display my iPhone on my computer monitor?

use screensplitr on jailbrocken iphone/ipod touch it works

Use cases for the 'setdefault' dict method

As Muhammad said, there are situations in which you only sometimes wish to set a default value. A great example of this is a data structure which is first populated, then queried.

Consider a trie. When adding a word, if a subnode is needed but not present, it must be created to extend the trie. When querying for the presence of a word, a missing subnode indicates that the word is not present and it should not be created.

A defaultdict cannot do this. Instead, a regular dict with the get and setdefault methods must be used.

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

Copy rows from one table to another, ignoring duplicates

Your problem is that you need another where clause in the subquery that identifies what makes a duplicate:

INSERT INTO destTable
SELECT Field1,Field2,Field3,... 
FROM srcTable
WHERE NOT EXISTS(SELECT * 
                 FROM destTable 
                 WHERE (srcTable.Field1=destTable.Field1 and
                       SrcTable.Field2=DestTable.Field2...etc.)
                 )

As noted by another answerer, an outer join is probably a more concise approach. My above example was just an attempt to explain using your current query to be more understandible. Either approach could technically work.

INSERT INTO destTable
SELECT s.field1,s.field2,s.field3,... 
FROM srcTable s 
       LEFT JOIN destTable d ON (d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...)
WHERE d.Key1 IS NULL

Both of the above approaches assume you are woried about inserting rows from source that might already be in destination. If you are instead concerned about the possibility that source has duplicate rows you should try something like.

INSERT INTO destTable
SELECT Distinct field1,field2,field3,... 
FROM srcTable  

One more thing. I'd also suggest listing the specific fields on your insert statement instead of using SELECT *.

Reset local repository branch to be just like remote repository HEAD

This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch

I also added an "are you sure" prompt, & some feedback output

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] || 
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
  git branch "auto-save-$branchname-at-$timestamp" 
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname

How to change the cursor into a hand when a user hovers over a list item?

Check the following. I get it from W3Schools.

_x000D_
_x000D_
.alias { cursor: alias; }
.all-scroll { cursor: all-scroll; }
.auto { cursor: auto; }
.cell { cursor: cell; }
.context-menu { cursor: context-menu; }
.col-resize { cursor: col-resize; }
.copy { cursor: copy; }
.crosshair { cursor: crosshair; }
.default { cursor: default; }
.e-resize { cursor: e-resize; }
.ew-resize { cursor: ew-resize; }
.grab {
  cursor: -webkit-grab;
  cursor: grab;
}
.grabbing {
  cursor: -webkit-grabbing;
  cursor: grabbing;
}
.help { cursor: help; }
.move { cursor: move; }
.n-resize { cursor: n-resize; }
.ne-resize { cursor: ne-resize; }
.nesw-resize { cursor: nesw-resize; }
.ns-resize { cursor: ns-resize; }
.nw-resize { cursor: nw-resize; }
.nwse-resize { cursor: nwse-resize; }
.no-drop { cursor: no-drop; }
.none { cursor: none; }
.not-allowed { cursor: not-allowed; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.row-resize { cursor: row-resize; }
.s-resize { cursor: s-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.text { cursor: text; }
.url { cursor: url(myBall.cur), auto; }
.w-resize { cursor: w-resize; }
.wait { cursor: wait; }
.zoom-in { cursor: zoom-in; }
.zoom-out { cursor: zoom-out; }
_x000D_
<!DOCTYPE html>
<html>

<body>
  <h1>The cursor property</h1>
  <p>Mouse over the words to change the mouse cursor.</p>
  <p class="alias">alias</p>
  <p class="all-scroll">all-scroll</p>
  <p class="auto">auto</p>
  <p class="cell">cell</p>
  <p class="context-menu">context-menu</p>
  <p class="col-resize">col-resize</p>
  <p class="copy">copy</p>
  <p class="crosshair">crosshair</p>
  <p class="default">default</p>
  <p class="e-resize">e-resize</p>
  <p class="ew-resize">ew-resize</p>
  <p class="grab">grab</p>
  <p class="grabbing">grabbing</p>
  <p class="help">help</p>
  <p class="move">move</p>
  <p class="n-resize">n-resize</p>
  <p class="ne-resize">ne-resize</p>
  <p class="nesw-resize">nesw-resize</p>
  <p class="ns-resize">ns-resize</p>
  <p class="nw-resize">nw-resize</p>
  <p class="nwse-resize">nwse-resize</p>
  <p class="no-drop">no-drop</p>
  <p class="none">none</p>
  <p class="not-allowed">not-allowed</p>
  <p class="pointer">pointer</p>
  <p class="progress">progress</p>
  <p class="row-resize">row-resize</p>
  <p class="s-resize">s-resize</p>
  <p class="se-resize">se-resize</p>
  <p class="sw-resize">sw-resize</p>
  <p class="text">text</p>
  <p class="url">url</p>
  <p class="w-resize">w-resize</p>
  <p class="wait">wait</p>
  <p class="zoom-in">zoom-in</p>
  <p class="zoom-out">zoom-out</p>
</body>

</html>
_x000D_
_x000D_
_x000D_

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

enter image description here

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Bootstrap 4

_x000D_
_x000D_
setResponsiveDivs();_x000D_
_x000D_
function setResponsiveDivs() {_x000D_
    var data = [_x000D_
        {id: 'visible-xs', class: 'd-block d-sm-none'},_x000D_
        {id: 'visible-sm', class: 'd-none d-sm-block d-md-none'},_x000D_
        {id: 'visible-md', class: 'd-none d-md-block d-lg-none'},_x000D_
        {id: 'visible-lg', class: 'd-none d-lg-block d-xl-none'},_x000D_
        {id: 'visible-xl', class: 'd-none d-xl-block'}_x000D_
    ];_x000D_
_x000D_
    for (var i = 0; i < data.length; i++) {_x000D_
        var el = document.createElement("div");_x000D_
        el.setAttribute('id', data[i].id);_x000D_
        el.setAttribute('class', data[i].class);_x000D_
        document.getElementsByTagName('body')[0].appendChild(el);_x000D_
    }_x000D_
}_x000D_
_x000D_
function isVisible(type) {_x000D_
    return window.getComputedStyle(document.getElementById('visible-' + type), null).getPropertyValue('display') === 'block';_x000D_
}_x000D_
_x000D_
// then, at some point_x000D_
window.onresize = function() {_x000D_
    console.log(isVisible('xs') === true ? 'xs' : '');_x000D_
    console.log(isVisible('sm') === true ? 'sm' : '');_x000D_
    console.log(isVisible('md') === true ? 'md' : '');_x000D_
    console.log(isVisible('lg') === true ? 'lg' : '');_x000D_
    console.log(isVisible('xl') === true ? 'xl' : '');_x000D_
};
_x000D_
_x000D_
_x000D_

or minified

_x000D_
_x000D_
function setResponsiveDivs(){for(var e=[{id:"visible-xs","class":"d-block d-sm-none"},{id:"visible-sm","class":"d-none d-sm-block d-md-none"},{id:"visible-md","class":"d-none d-md-block d-lg-none"},{id:"visible-lg","class":"d-none d-lg-block d-xl-none"},{id:"visible-xl","class":"d-none d-xl-block"}],s=0;s<e.length;s++){var l=document.createElement("div");l.setAttribute("id",e[s].id),l.setAttribute("class",e[s]["class"]),document.getElementsByTagName("body")[0].appendChild(l)}}function isVisible(e){return"block"===window.getComputedStyle(document.getElementById("visible-"+e),null).getPropertyValue("display")}setResponsiveDivs();
_x000D_
_x000D_
_x000D_

Is there a function to round a float in C or do I need to write my own?

Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf().

I think there is another way to do it, though. You can try ceil() and floor() to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil() and floor() only work on doubles though.

EDIT: Also, for floats, you can use truncf() to truncate floats. The same +0.5 trick should work to do accurate rounding.

How to create a sub array from another array in Java?

Use copyOfRange method from java.util.Arrays class:

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

For more details:

Link to similar question

Append a tuple to a list - what's the difference between two ways?

I believe tuple() takes a list as an argument For example,

tuple([1,2,3]) # returns (1,2,3)

see what happens if you wrap your array with brackets

How to remove elements/nodes from angular.js array

Using the indexOf function was not cutting it on my collection of REST resources.

I had to create a function that retrieves the array index of a resource sitting in a collection of resources:

factory.getResourceIndex = function(resources, resource) {
  var index = -1;
  for (var i = 0; i < resources.length; i++) {
    if (resources[i].id == resource.id) {
      index = i;
    }
  }
  return index;
}

$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);

How to identify a strong vs weak relationship on ERD?

  1. Weak (Non-Identifying) Relationship

    • Entity is existence-independent of other enties

    • PK of Child doesn’t contain PK component of Parent Entity

  2. Strong (Identifying) Relationship

    • Child entity is existence-dependent on parent

    • PK of Child Entity contains PK component of Parent Entity

    • Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.

Set environment variables on Mac OS X Lion

Setup your PATH environment variable on Mac OS

Open the Terminal program (this is in your Applications/Utilites folder by default). Run the following command

touch ~/.bash_profile; open ~/.bash_profile

This will open the file in the your default text editor.

For ANDROID SDK as example :

You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use "/Development/android-sdk-macosx" as the directory the SDK is installed in. Add the following line:

export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools

Save the file and quit the text editor. Execute your .bash_profile to update your PATH.

source ~/.bash_profile

Now everytime you open the Terminal program you PATH will included the Android SDK.

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

Use of #pragma in C

Putting #pragma once at the top of your header file will ensure that it is only included once. Note that #pragma once is not standard C99, but supported by most modern compilers.

An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */)

Disabling the button after once click

think simple

<button id="button1" onclick="Click();">ok</button>
<script>
    var buttonClick = false;
    function Click() {
        if (buttonClick) {
            return;
        }
        else {
            buttonClick = true;
            //todo
            alert("ok");
            //buttonClick = false;
        }
    }
</script>

if you want run once :)

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I solve it running:

chmod 400 ~/.ssh/id_rsa

I hope to help. Good luck.

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>

or

$sidemenus = mysql_fetch_array($results);

then

<?php echo $sidemenu['mname']."<br />";?>

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

Adding certificates to Java\jdk\jre\lib\security folder worked for me. If you are using Chrome click on the green bulb [https://support.google.com/chrome/answer/95617?p=ui_security_indicator&rd=1] and save the certificate in security folder.

How to store JSON object in SQLite database

https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1

As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.

How to fix "Attempted relative import in non-package" even with __init__.py

As Paolo said, we have 2 invocation methods:

1) python -m tests.core_test
2) python tests/core_test.py

One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py:

if __name__ == '__main__':
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from components import core
    <other stuff>

And more after this, we can run core_test.py with other methods:

cd tests
python core_test.py
python -m core_test
...

Note, py36 tested only.

Adding devices to team provisioning profile

For Xcode 6 it is a little different.

After adding the device UDID in the developer site (https://developer.apple.com/account/ios/device/deviceList.action), go back to Xcode.

Xcode -> Preferences -> Accounts Select the Apple ID you added the device under and in the bottom right, click "View Details..."

Hit the refresh icon on the bottom left and then try to run the app again.

Email Address Validation for ASP.NET

You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Insert a line break in mailto body

<a href="mailto:[email protected]?subject=Request&body=Hi,%0DName:[your name] %0DGood day " target="_blank"></a>

Try adding %0D to break the line. This will definitely work.

Above code will display the following:

Hi,
Name:[your name] 
Good day

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

Java get last element of a collection

This should work without converting to List/Array:

collectionName.stream().reduce((prev, next) -> next).orElse(null)

Convert base-2 binary number string to int

You use the built-in int function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for python2, and for python3.

How can I render repeating React elements?

To expand on Ross Allen's answer, here is a slightly cleaner variant using ES6 arrow syntax.

{this.props.titles.map(title =>
  <th key={title}>{title}</th>
)}

It has the advantage that the JSX part is isolated (no return or ;), making it easier to put a loop around it.

How do I format a date as ISO 8601 in moment.js?

Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

This is what I used based on your function. I prefer to use steps over percentage because it's more intuitive for me.

For example, 20% of a 200 blue value is much different than 20% of a 40 blue value.

Anyways, here's my modification, thanks for your original function.

function adjustBrightness(col, amt) {

    var usePound = false;

    if (col[0] == "#") {
        col = col.slice(1);
        usePound = true;
    }

    var R = parseInt(col.substring(0,2),16);
    var G = parseInt(col.substring(2,4),16);
    var B = parseInt(col.substring(4,6),16);

    // to make the colour less bright than the input
    // change the following three "+" symbols to "-"
    R = R + amt;
    G = G + amt;
    B = B + amt;

    if (R > 255) R = 255;
    else if (R < 0) R = 0;

    if (G > 255) G = 255;
    else if (G < 0) G = 0;

    if (B > 255) B = 255;
    else if (B < 0) B = 0;

    var RR = ((R.toString(16).length==1)?"0"+R.toString(16):R.toString(16));
    var GG = ((G.toString(16).length==1)?"0"+G.toString(16):G.toString(16));
    var BB = ((B.toString(16).length==1)?"0"+B.toString(16):B.toString(16));

    return (usePound?"#":"") + RR + GG + BB;

}

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

How to convert a string with Unicode encoding to a string of letters

You can use StringEscapeUtils from Apache Commons Lang, i.e.:

String Title = StringEscapeUtils.unescapeJava("\\u0048\\u0065\\u006C\\u006C\\u006F");

403 Forbidden You don't have permission to access /folder-name/ on this server

Solved issue using below steps :

1) edit file "/etc/apache2/sites-enabled/000-default.conf"

    DocumentRoot "dir_name"

    ServerName <server_IP>

    <Directory "dir_name">
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
    </Directory>

    <Directory "dir_name">
       AllowOverride None
       # Allow open access:
       Require all granted

2) change folder permission sudo chmod -R 777 "dir_name"

Run .jar from batch-file

Just the same way as you would do in command console. Copy exactly those commands in the batch file.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

You should also ensure you set a reference to WindowsBase. This is required to use the SDK as it handles System.IO.Packaging (which is used for unzipping and opening the compressed .docx/.xlsx/.pptx as an OPC document).

How to obtain the total numbers of rows from a CSV file in Python?

import csv
count = 0
with open('filename.csv', 'rb') as count_file:
    csv_reader = csv.reader(count_file)
    for row in csv_reader:
        count += 1

print count

Tab separated values in awk

Use:

awk -v FS='\t' -v OFS='\t' ...

Example from one of my scripts.

I use the FS and OFS variables to manipulate BIND zone files, which are tab delimited:

awk -v FS='\t' -v OFS='\t' \
    -v record_type=$record_type \
    -v hostname=$hostname \
    -v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp

This is a clean and easy to read way to do this.

ASP.NET MVC3 - textarea with @Html.EditorFor

Declare in your Model with

  [DataType(DataType.MultilineText)]
  public string urString { get; set; }

Then in .cshtml can make use of editor as below. you can make use of @cols and @rows for TextArea size

     @Html.EditorFor(model => model.urString, new { htmlAttributes = new { @class = "",@cols = 35, @rows = 3 } })

Thanks !

How do you clear the focus in javascript?

With jQuery its just: $(this).blur();

How to turn off page breaks in Google Docs?

The only way to remove the dotted line (to my knowledge) is with css hacking using plugin.

  • Install the User CSS (or User JS & CSS) plugin, which allows adding CSS rules per site.

  • Once on Google Docs, click the plugins icon, toggle the OFF to ON button, and add the following css code:

.

.kix-page-compact::before{
    border-top: none;
}

enter image description here

Should work like a charm.

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

You're confusing PATH and PYTHONPATH. You need to do this:

export PATH=$PATH:/home/randy/lib/python 

PYTHONPATH is used by the python interpreter to determine which modules to load.

PATH is used by the shell to determine which executables to run.

How do I disable right click on my web page?

Of course, as per all other comments here, this simply doesn't work.

I did once construct a simple java applet for a client which forced any capture of of an image to be done via screen capture and you might like to consider a similar technique. It worked, within the limitations, but I still think it was a waste of time.

Set title background color

I have done this by changing style color values in "res" -> "values" -> "colors.xml" enter image description here

This will change colors for entire project which is fine with me.

enter image description here

Delayed rendering of React components

Depends on your use case.

If you want to do some animation of children blending in, use the react animation add-on: https://facebook.github.io/react/docs/animation.html Otherwise, make the rendering of the children dependent on props and add the props after some delay.

I wouldn't delay in the component, because it will probably haunt you during testing. And ideally, components should be pure.

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

Java equivalent to Explode and Implode(PHP)

The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.

Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:

String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
    sb.append(split[i]);
    if (i != split.length - 1) {
        sb.append(" ");
    }
}
String joined = sb.toString();

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

Could not load NIB in bundle

Got this problem while transforming my old code from XCode 3x to XCode 4 and Solved it by just renaming wwwwwwww.xib into RootViewController.xib

ASP.NET MVC - Extract parameter of an URL

public ActionResult Index(int id,string value)

This function get values form URL After that you can use below function

Request.RawUrl - Return complete URL of Current page

RouteData.Values - Return Collection of Values of URL

Request.Params - Return Name Value Collections

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

How do I read all classes from a Java package in the classpath?

Java 1.6.0_24:

public static File[] getPackageContent(String packageName) throws IOException{
    ArrayList<File> list = new ArrayList<File>();
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                            .getResources(packageName);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        File dir = new File(url.getFile());
        for (File f : dir.listFiles()) {
            list.add(f);
        }
    }
    return list.toArray(new File[]{});
}

This solution was tested within the EJB environment.

SQL to find the number of distinct values in a column

Be aware that Count() ignores null values, so if you need to allow for null as its own distinct value you can do something tricky like:

select count(distinct my_col)
       + count(distinct Case when my_col is null then 1 else null end)
from my_table
/

Fatal error: "No Target Architecture" in Visual Studio

It would seem that _AMD64_ is not defined, since I can't imagine you are compiling for Itanium (_IA64_).

Case insensitive regular expression without re.compile?

If you would like to replace but still keeping the style of previous str. It is possible.

For example: highlight the string "test asdasd TEST asd tEst asdasd".

sentence = "test asdasd TEST asd tEst asdasd"
result = re.sub(
  '(test)', 
  r'<b>\1</b>',  # \1 here indicates first matching group.
  sentence, 
  flags=re.IGNORECASE)

test asdasd TEST asd tEst asdasd

How does BitLocker affect performance?

My current work machine came with bitlocker, and being an upgrade from the prior model. It only seemed faster to me. What I have found, however, is that bitlocker is more bullet proof than truecrypt, when it comes to accurately laying down the data. I do a lot of work in SAS which constantly writes backup copies to disk as it moves along and shoots a variety of output types to disk at the end. SAS works fine writing output from multithreaded processes back to bitlocker and doesn't seem to know it's there. This has not been the case for me with truecrypt. I'm not sure what happens or how, but I found that processes got out of synch when working with source/output data in a truecrypt container, which is what I installed on my second work computer since it had no bitlocker. The constant backups were shooting to an SSD while the truecrypt results were on a regular HD. Maybe that speed difference helped trip it up. Whatever the cause, I had to quit using truecrypt on that second computer because it made my SAS results out of synch with respect to processing order and it screwed up some of my processes and data. Scary stuff in my world.

I work with people who have successfully used Truecrypt on the exact same computer, but they weren't using a disk intensive app. like SAS.

Bitlocker to Go, the encryption which bitlocker applies to thumb-drives, does slow things down quite a bit when it comes to read/write times. It's not too hard to use as long as you remember your password on the thumbdrive, and are willing to wait for it to format/initialize the drive, but in my experience it made access to the flash drive about 4 times as slow. Don't know why it would slow down a thumb drive and not a disk but that's how it was for me and my coworker.

Based on my success with bitlocker at work, I bought Windows Pro for my home computer to get bitlocker and plan to encrypt some directories with it for things like financials.

I can not find my.cnf on my windows computer

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

Unused arguments in R

Change the definition of multiply to take additional unknown arguments:

multiply <- function(a, b, ...) {
  # Original code
}

How to get the difference between two arrays of objects in JavaScript

For those who like one-liner solutions in ES6, something like this:

_x000D_
_x000D_
const arrayOne = [ _x000D_
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },_x000D_
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },_x000D_
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },_x000D_
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },_x000D_
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },_x000D_
];_x000D_
          _x000D_
const arrayTwo = [_x000D_
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},_x000D_
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},_x000D_
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},_x000D_
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},_x000D_
];_x000D_
_x000D_
const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1));_x000D_
_x000D_
console.log(results);
_x000D_
_x000D_
_x000D_

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

mysql said: Cannot connect: invalid settings. xampp

I also have the problem but now solved

$cfg['Servers'][$i]['user'] = 'admin'; - I change the user name from 'root' to 'admin'

Toggle input disabled attribute using jQuery


    $('#checkbox').click(function(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

Why Git is not allowing me to commit even after configuration?

Do you have a local user.name or user.email that's overriding the global one?

git config --list --global | grep user
  user.name=YOUR NAME
  user.email=YOUR@EMAIL
git config --list --local | grep user
  user.name=YOUR NAME
  user.email=

If so, remove them

git config --unset --local user.name
git config --unset --local user.email

The local settings are per-clone, so you'll have to unset the local user.name and user.email for each of the repos on your machine.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

Remove scrollbar from iframe

Try adding scrolling="no" attribute like below:

_x000D_
_x000D_
<iframe frameborder="0" scrolling="no" style="height:380px;width:6000px;border:none;" src='https://yoururl'></iframe>
_x000D_
_x000D_
_x000D_

The equivalent of a GOTO in python

Forgive me - I couldn't resist ;-)

def goto(linenum):
    global line
    line = linenum

line = 1
while True:
    if line == 1:
        response = raw_input("yes or no? ")
        if response == "yes":
            goto(2)
        elif response == "no":
            goto(3)
        else:
            goto(100)
    elif line == 2:
        print "Thank you for the yes!"
        goto(20)
    elif line == 3:
        print "Thank you for the no!"
        goto(20)
    elif line == 20:
        break
    elif line == 100:
        print "You're annoying me - answer the question!"
        goto(1)

Print empty line?

You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).

Trust in the error message -- if it says something specific, assume it to be true and figure out why.

Remove excess whitespace from within a string

Not sure exactly what you want but here are two situations:

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.

  2. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".

Example:

$foo = preg_replace('/\s+/', ' ', $foo);

Python extending with - using super() Python 3 vs Python 2

  • super() (without arguments) was introduced in Python 3 (along with __class__):

    super() -> same as super(__class__, self)
    

    so that would be the Python 2 equivalent for new-style classes:

    super(CurrentClass, self)
    
  • for old-style classes you can always use:

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    

load csv into 2D matrix with numpy for plotting

Pure numpy

numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)

Check out the loadtxt documentation.

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

Added Hint:

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

What is __pycache__?

A __pycache__ folder is created when you use the line:

import file_name

or try to get information from another file you have created. This makes it a little faster when running your program the second time to open the other file.

Comment shortcut Android Studio

Mac With Numeric pad

Line Comment hold both: Cmd + /

Block Comment hold all three: Cmd + Alt + /

Mac

Line Comment hold both: Cmd + + =

Block Comment hold all three: Cmd + Alt + + =


Windows/linux :

Line Comment hold both: Ctrl + /

Block Comment hold all three: Ctrl + Shift + /

Same way to remove the comment block.


To Provide Method Documentation comment type /** and press Enter just above the method name (

It will create a block comment with parameter list and return type like this

/**
 * @param userId 
 * @return
 */
public int getSubPlayerCountForUser(String userId){}

Setting DEBUG = False causes 500 Error

I know this post is quite old but it's still perfectly relevant today.

For what it's worth - I was getting a 500 with DEBUG = False for all pages on my site.

I got no traceback when in debug.

I had to go through every static link in my templates within my site and found one / (forward slash) in front of my image source. {% static ... %}. This caused the 500 error in DEBUG = False but worked perfectly fine in Debug = True with no errors. Very annoying! Be warned! Many hours of time wasted due to a forward slash...