Programs & Examples On #Rpg

DO NOT use this tag for Role Playing Games!! RPG is a high-level programming language (HLL) for business applications, initials which stand for Report Program Generator. IBM is the creator and primary vendor of RPG, but the language is available from other mainframe and microcomputer manufacturers, including Unisys. Use this tag for older non-ILE versions of RPG from IBM and for non-IBM variants of the language.

Visual Studio 2017 errors on standard headers

I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.

I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

TypeError: can only concatenate list (not "str") to list

I have a solution for this. First thing that add is already having a string value as input() function by default takes the input as string. Second thing that you can use append method to append value of add variable in your list.

Please do check my code I have done some modification : - {1} You can enter command in capital or small or mix {2} If user entered wrong command then your program will ask to input command again

inventory = ["sword","potion","armour","bow"] print(inventory) print("\ncommands : use (remove item) and pickup (add item)") selection=input("choose a command [use/pickup] : ") while True: if selection.lower()=="use": print(inventory) remove_item=input("What do you want to use? ") inventory.remove(remove_item) print(inventory) break

 elif selection.lower()=="pickup":
      print(inventory)
      add_item=input("What do you want to pickup? ")
      inventory.append(add_item)
      print(inventory)
      break
 
 else:
      print("Invalid Command. Please check your input")
      selection=input("Once again choose a command [use/pickup] : ")

Getting RSA private key from PEM BASE64 Encoded private key file

Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.

String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
    .replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data

byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);

try {
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
        .fromByteArray(encodedPrivateKey);
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException("wrong version for RSA private key");
    }
    /**
     * In fact only modulus and private exponent are in use.
     */
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();

    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);
}

Java - remove last known item from ArrayList

The compiler complains that you are trying something of a list of ClientThread objects to a String. Either change the type of hey to ClientThread or clients to List<String>.

In addition: Valid indices for lists are from 0 to size()-1.

So you probably want to write

   String hey = clients.get(clients.size()-1);

What is the worst programming language you ever worked with?

In the mid 90’s I worked in a small management consulting firm using a GIS product called MapInfo which had a weak scripting language called MapBasic.

I don’t remember the specifics, but basically at that time there were objects* which could only be instantiated when hard coded (as opposed to instantiating with variables). This was a total pain in that it appeared to do everything you needed done, until you actually attempted to implement. Implementation was either impossible or very kludge heavy.

I was a novice at that point and had a lot of difficulty a) predicting what could and could not be done, and b) explaining why to my non-programming manager. It was frustrating none the less.

There are a lot of languages and tools which are weak in certain areas, but after dealing with Map Basic, even Visual Basic 3.0 felt liberating!

*-I don’t remember if it was all objects or only certain ones.

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

CREATE DATABASE permission denied in database 'master' (EF code-first)

the reason for this error may be originate from forwarding of version dependent localdb in visual sudio 2013 to the version independent localDB in VS 2015 onwards, so simply change your web.config file connectionStrings from (localDb)\v11.0 to (localDB)\MSSQLLocalDB and it will certainly work. and this is a good explaination for that Version independent local DB in Visual Studio 2015

Java: How to convert String[] to List or Set

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

Changing the default title of confirm() in JavaScript?

You can't unfortunately. The only way is to simulate this with a window.open call.

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

Apply pandas function to column to create multiple new columns?

This is what I've done in the past

df = pd.DataFrame({'textcol' : np.random.rand(5)})

df
    textcol
0  0.626524
1  0.119967
2  0.803650
3  0.100880
4  0.017859

df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))
   feature1  feature2
0  1.626524 -0.373476
1  1.119967 -0.880033
2  1.803650 -0.196350
3  1.100880 -0.899120
4  1.017859 -0.982141

Editing for completeness

pd.concat([df, df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))], axis=1)
    textcol feature1  feature2
0  0.626524 1.626524 -0.373476
1  0.119967 1.119967 -0.880033
2  0.803650 1.803650 -0.196350
3  0.100880 1.100880 -0.899120
4  0.017859 1.017859 -0.982141

How do I move files in node.js?

This example taken from: Node.js in Action

A move() function that renames, if possible, or falls back to copying

var fs = require('fs');

module.exports = function move(oldPath, newPath, callback) {

    fs.rename(oldPath, newPath, function (err) {
        if (err) {
            if (err.code === 'EXDEV') {
                copy();
            } else {
                callback(err);
            }
            return;
        }
        callback();
    });

    function copy() {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', callback);
        writeStream.on('error', callback);

        readStream.on('close', function () {
            fs.unlink(oldPath, callback);
        });

        readStream.pipe(writeStream);
    }
}

Where does forever store console.log output?

You need to add the log destination specifiers before the filename to run. So

forever -e /path/error.txt -o /path/output.txt start index.js

Where do alpha testers download Google Play Android apps?

  1. Publish your alpha apk by pressing the submit button.

  2. Wait until it's published.
    (e.g.: CURRENT APK published on Apr 28, 2015, 2:20:13AM)

  3. Select Alpha testers - click Manage list of testers.

  4. Share the link with your testers (by email).
    (e.g.: https://play.google.com/apps/testing/uk.co.xxxxx.xxxxx)

How to avoid a System.Runtime.InteropServices.COMException?

Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.

You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException. Tick the option to break when it's thrown and then debug your application.

Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

jquery variable syntax

$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.

example:

var self = 'some string';
var $self = 'another string';

These are declared as two different variables. It's like putting underscore before private variables.

A somewhat popular pattern is:

var foo = 'some string';
var $foo = $('.foo');

That way, you know $foo is a cached jQuery object later on in the code.

Determine on iPhone if user has enabled push notifications

Swift 3+

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            // settings.authorizationStatus == .authorized
        })
    } else {
        return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
    }

RxSwift Observable Version for iOS10+:

import UserNotifications
extension UNUserNotificationCenter {
    static var isAuthorized: Observable<Bool> {
        return Observable.create { observer in
            DispatchQueue.main.async {
                current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
                    if settings.authorizationStatus == .authorized {
                        observer.onNext(true)
                        observer.onCompleted()
                    } else {
                        current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
                            observer.onNext(granted)
                            observer.onCompleted()
                        }
                    }
                })
            }
            return Disposables.create()
        }
    }
}

How to clamp an integer to some range?

See numpy.clip:

index = numpy.clip(index, 0, len(my_list) - 1)

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

in my case

<section name="entityFramework"

must be updated from version 4 to 6. I mean a project was updated EntityFramework from 4 to 6 but web.config was not updated.

How to make a page redirect using JavaScript?

You can achieve this using the location object.

location.href = "http://someurl"; 

ORA-01861: literal does not match format string

Remove the TO_DATE in the WHERE clause

TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')

and change the code to

alarm_datetime

The error comes from to_date conversion of a date column.

Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

Removing duplicates from a list of lists

This should work.

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

k_cleaned = []
for ele in k:
    if set(ele) not in [set(x) for x in k_cleaned]:
        k_cleaned.append(ele)
print(k_cleaned)

# output: [[1, 2], [4], [5, 6, 2], [3]]

100% width background image with an 'auto' height

Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:

body {
    background-image: url(img.jpg);
    background-position: center top;
    background-size: 100% auto;
}

This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.

EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.

Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.

However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:

.foo {
    height: 0;
    padding: 0; /* remove any pre-existing padding, just in case */
    padding-bottom: 75%; /* for a 4:3 aspect ratio */
    background-image: url(foo.png);
    background-position: center center;
    background-size: 100%;
    background-repeat: no-repeat;
}

In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.

jQuery 'input' event

Be Careful while using INPUT. This event fires on focus and on blur in IE 11. But it is triggered on change in other browsers.

https://connect.microsoft.com/IE/feedback/details/810538/ie-11-fires-input-event-on-focus

C# Interfaces. Implicit implementation versus Explicit implementation

I use explicit interface implementation most of the time. Here are the main reasons.

Refactoring is safer

When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.

Two common cases come to mind:

  • Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).

  • Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.

It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.

Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.

It's self-documenting

If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..

Whereas: 'bool ITask.Execute()' is clear and unambiguous.

Clear separation of interface implementation

I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.

As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).

(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)

Related: Reason 2 above by Jon.

And so on

Plus the advantages already mentioned in other answers here:

Problems

It's not all fun and happiness. There are some cases where I stick with implicits:

  • Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
  • Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).

Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:

  1. Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
  2. (My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).

X-Frame-Options: ALLOW-FROM in firefox and chrome

For Chrome, instead of

response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);

you need to add Content-Security-Policy

string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);

to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from header for Chrome (outputs error on console).

For details, see my answer here.

Using grep to search for hex strings in a file

We tried several things before arriving at an acceptable solution:

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....


root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....

Then found we could get usable results with

xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd

Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....
--------------------^^

So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).

The final result seems to be

xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex

0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF  ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03  .$.q............
--------------------------------------------^^

Eclipse : Maven search dependencies doesn't work

For me for this issue worked to:

  • remove ~/.m2
  • enable "Full Index Enabled" in maven repository view on central repository
  • "Rebuild Index" on central maven repository

After eclipse restart everything worked well.

How to make PDF file downloadable in HTML link?

if you need to limit download rate, use this code !!

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
    // send the current file part to the browser
    print fread($file, round($download_rate * 1024));
    // flush the content to the browser
    flush();
    // sleep one second
    sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}

?>

For more information click here

Get first date of current month in java

If you also want the time is set to 0 the code is:

import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}

You can check online easily without compiling by using: http://www.browxy.com/

Cleanest way to reset forms

Angular Reactive Forms:

onCancel(): void {
  this.registrationForm.reset();
  this.registrationForm.controls['name'].setErrors(null);
  this.registrationForm.controls['email'].setErrors(null);
}

how to change any data type into a string in python

Just use str - for example:

>>> str([])
'[]'

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

After following @Neelam Verma's answer or @dawid's answer, which has the same end result as @Neelam Verma's answer, difference being that @dawid's answer starts with the drag and drop of the file into the Xcode project and @Neelam Verma's answer starts with a file already a part of the Xcode project, I still could not get NSBundle.mainBundle().pathForResource("file-title", ofType:"type") to find my video file.

I thought maybe because I had my file was in a Group nested in the Xcode project that this was the cause, so I moved the video file to the root of my Xcode project, still no luck, this was my code:

 guard let path = NSBundle.mainBundle().pathForResource("testVid1", ofType:"mp4") else {
        print("Invalid video path")
        return
    }

Originally, this was the name of my file: testVid1.MP4, renaming the video file to testVid1.mp4 fixed my issue, so, at least the ofType string argument is case sensitive.

Hashing a file in Python

I would propose simply:

def get_digest(file_path):
    h = hashlib.sha256()

    with open(file_path, 'rb') as file:
        while True:
            # Reading is buffered, so we can read smaller chunks.
            chunk = file.read(h.block_size)
            if not chunk:
                break
            h.update(chunk)

    return h.hexdigest()

All other answers here seem to complicate too much. Python is already buffering when reading (in ideal manner, or you configure that buffering if you have more information about underlying storage) and so it is better to read in chunks the hash function finds ideal which makes it faster or at lest less CPU intensive to compute the hash function. So instead of disabling buffering and trying to emulate it yourself, you use Python buffering and control what you should be controlling: what the consumer of your data finds ideal, hash block size.

How can I limit the visible options in an HTML <select> dropdown?

Tnx @Raj_89 , Your trick was very good , can be better , only by use extra style , that make it on other dom objects , exactly like a common select option tag in html ...

select{
 position:absolute;
}

u can see result here : http://jsfiddle.net/aTzc2/

How to use pip on windows behind an authenticating proxy

I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY with cmd :

set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
pip install <packagename>

You have to use double quotes and set NO_PROXY to upper case. You can also add NO_PROXY as an environment variable instead of setting it each time you use the console.

I hope this will help if any other solution posted here works.

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

Singleton design pattern vs Singleton beans in Spring container

Singleton scope in spring means single instance in a Spring context ..
Spring container merely returns the same instance again and again for subsequent calls to get the bean.


And spring doesn't bother if the class of the bean is coded as singleton or not , in fact if the class is coded as singleton whose constructor as private, Spring use BeanUtils.instantiateClass (javadoc here) to set the constructor to accessible and invoke it.

Alternatively, we can use a factory-method attribute in bean definition like this

    <bean id="exampleBean" class="example.Singleton"  factory-method="getInstance"/>

How to select first child with jQuery?

Hi we can use default method "first" in jQuery

Here some examples:

When you want to add class for first div

  $('.alldivs div').first().addClass('active');

When you want to change the remove the "onediv" class and add only to first child

   $('.alldivs div').removeClass('onediv').first().addClass('onediv');

Launch an app from within another (iPhone)

You can only launch apps that have registered a URL scheme. Then just like you open the SMS app by using sms:, you'll be able to open the app using their URL scheme.

There is a very good example available in the docs called LaunchMe which demonstrates this.

LaunchMe sample code as of 6th Nov 2017.

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

How do you overcome the svn 'out of date' error?

Tried all but change in .svn directly. Nothing helped so here's my solution.

In Eclipse > Window > Show View > History I've seen that file is not at the newest Revision, although I made multiple svn "Override & Update" / "Revert" / delete file and checkout.

So I went Package Explorer > Right click on file > Replace with > Latest from Repository.

Another look in the History View showed that file was now on latest Revision.

1064 error in CREATE TABLE ... TYPE=MYISAM

As documented under CREATE TABLE Syntax:

Note
The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

Therefore, you want:

CREATE TABLE dave_bannedwords(
  id   INT(11)     NOT NULL AUTO_INCREMENT,
  word VARCHAR(60) NOT NULL DEFAULT '',
  PRIMARY KEY (id),
  KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

Node.js spawn child process and get terminal output live

I'm still getting my feet wet with Node.js, but I have a few ideas. first, I believe you need to use execFile instead of spawn; execFile is for when you have the path to a script, whereas spawn is for executing a well-known command that Node.js can resolve against your system path.

1. Provide a callback to process the buffered output:

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], function(err, stdout, stderr) { 
    // Node.js will invoke this callback when process terminates.
    console.log(stdout); 
});  

2. Add a listener to the child process' stdout stream (9thport.net)

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3' ]); 
// use event hooks to provide a callback to execute when data are available: 
child.stdout.on('data', function(data) {
    console.log(data.toString()); 
});

Further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. I haven't tested this yet, but there are examples in the API docs that go something like this:

child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], { 
    // detachment and ignored stdin are the key here: 
    detached: true, 
    stdio: [ 'ignore', 1, 2 ]
}); 
// and unref() somehow disentangles the child's event loop from the parent's: 
child.unref(); 
child.stdout.on('data', function(data) {
    console.log(data.toString()); 
});

How to test an Oracle Stored Procedure with RefCursor return type?

In Toad 10.1.1.8 I use:

variable salida refcursor
exec MY_PKG.MY_PRC(1, 2, 3, :salida)  -- 1, 2, 3 are params
print salida

Then, Execute as Script.

Android: How can I validate EditText input?

This was nice solution from here

InputFilter filter= new InputFilter() { 
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
        for (int i = start; i < end; i++) { 
            String checkMe = String.valueOf(source.charAt(i));

            Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
            Matcher matcher = pattern.matcher(checkMe);
            boolean valid = matcher.matches();
            if(!valid){
                Log.d("", "invalid");
                return "";
            }
        } 
        return null; 
    } 
};

edit.setFilters(new InputFilter[]{filter}); 

Splitting a continuous variable into equal sized groups

Or see cut_number from the ggplot2 package, e.g.

das$wt_2 <- as.numeric(cut_number(das$wt,3))

Note that cut(...,3) divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number does by using quantile appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2() using the g= argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number. I might have thought that something like cut_number would have made its way into dplyr by so far, but as far as I can tell it hasn't.

How to copy files across computers using SSH and MAC OS X Terminal

You may also want to look at rsync if you're doing a lot of files.

If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

For completeness, in python 3.6 f-string are introduced in PEP-498. These strings make it possible to

embed expressions inside string literals, using a minimal syntax.

That would mean that for your example you could also use:

f'{self.author} in {self.publication}'

How to inspect Javascript Objects

Use your console:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

How to Add Date Picker To VBA UserForm

OFFICE 2013 INSTRUCTIONS:

(For Windows 7 (x64) | MS Office 32-Bit)

Option 1 | Check if ability already exists | 2 minutes

  1. Open VB Editor
  2. Tools -> Additional Controls
  3. Select "Microsoft Monthview Control 6.0 (SP6)" (if applicable)
  4. Use 'DatePicker' control for VBA Userform

Option 2 | The "Monthview" Control doesn't currently exist | 5 minutes

  1. Close Excel
  2. Download MSCOMCT2.cab (it's a cabinet file which extracts into two useful files)
  3. Extract Both Files | the .inf file and the .ocx file
  4. Install | right-click the .inf file | hit "Install"
  5. Move .ocx file | Move from "C:\Windows\system32" to "C:\Windows\sysWOW64"
  6. Run CMD | Start Menu -> Search -> "CMD.exe" | right-click the icon | Select "Run as administrator"
  7. Register Active-X File | Type "regsvr32 c:\windows\sysWOW64\MSCOMCT2.ocx"
  8. Open Excel | Open VB Editor
  9. Activate Control | Tools->References | Select "Microsoft Windows Common Controls 2-6.0 (SP6)"
  10. Userform Controls | Select any userform in VB project | Tools->Additional Controls
  11. Select "Microsoft Monthview Control 6.0 (SP6)"
  12. Use 'DatePicker' control for VBA UserForm

Okay, either of these two steps should work for you if you have Office 2013 (32-Bit) on Windows 7 (x64). Some of the steps may be different if you have a different combo of Windows 7 & Office 2013.

The "Monthview" control will be your fully fleshed out 'DatePicker'. It comes equipped with its own properties and image. It works very well. Good luck.

Site: "bonCodigo" from above (this is an updated extension of his work)
Site: "AMM" from above (this is just an exension of his addition)
Site: Various Microsoft Support webpages

Style child element when hover on parent

you can use this too

_x000D_
_x000D_
.parent:hover * {
   /* ... */
}
_x000D_
_x000D_
_x000D_

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

XMLHttpRequest status 0 (responseText is empty)

Consider also the request timeout:

Modern browser return readyState=4 and status=0 if too much time passes before the server response.

How does internationalization work in JavaScript?

Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is

an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.

Their js implementation is on the github L20n repository.

In Laravel, the best way to pass different types of flash messages in the session

Not a big fan of the solutions provided (ie: multiple variables, helper classes, looping through 'possibly existing variables'). Below is a solution that instead uses an array as opposed to two separate variables. It's also easily extendable to handle multiple errors should you wish but for simplicity, I've kept it to one flash message:

Redirect with flash message array:

    return redirect('/admin/permissions')->with('flash_message', ['success','Updated Successfully','Permission "'. $permission->name .'" updated successfully!']);

Output based on array content:

@if(Session::has('flash_message'))
    <script type="text/javascript">
        jQuery(document).ready(function(){
            bootstrapNotify('{{session('flash_message')[0]}}','{{session('flash_message')[1]}}','{{session('flash_message')[2]}}');
        });
    </script>
@endif

Unrelated since you might have your own notification method/plugin - but just for clarity - bootstrapNotify is just to initiate bootstrap-notify from http://bootstrap-notify.remabledesigns.com/:

function bootstrapNotify(type,title = 'Notification',message) {
    switch (type) {
        case 'success':
            icon = "la-check-circle";
            break;
        case 'danger':
            icon = "la-times-circle";
            break;
        case 'warning':
            icon = "la-exclamation-circle";
    }

    $.notify({message: message, title : title, icon : "icon la "+ icon}, {type: type,allow_dismiss: true,newest_on_top: false,mouse_over: true,showProgressbar: false,spacing: 10,timer: 4000,placement: {from: "top",align: "right"},offset: {x: 30,y: 30},delay: 1000,z_index: 10000,animate: {enter: "animated bounce",exit: "animated fadeOut"}});
}

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Probably you didn't add your room class to child RoomDatabase child class in @Database(entities = {your_classes})

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;.

    $(window).on("load",function() {
    function fade() {
        var animation_height = $(window).innerHeight() * 0.25;
        var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;

        $('.fade').each(function() {

            var objectTop = $(this).offset().top;
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            if ( objectTop < windowBottom ) {
                if ( objectTop < windowBottom - animation_height ) {
                    $(this).html( 'fully visible' );
                    $(this).css( {
                        transition: 'opacity 0.1s linear',
                        opacity: 1
                    } );

                } else {
                    $(this).html( 'fading in/out' );
                    $(this).css( {
                        transition: 'opacity 0.25s linear',
                        opacity: (windowBottom - objectTop) * ratio
                    } );
                }
            } else {
                $(this).html( 'not visible' );
                $(this).css( 'opacity', 0 );
            }
        });
    }
    $('.fade').css( 'opacity', 0 );
    fade();
    $(window).scroll(function() {fade();});
});

See it here: http://jsfiddle.net/78xjLnu1/16/

Cheers, Martin

Pretty-Printing JSON with PHP

PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.

http://php.net/manual/en/function.json-encode.php

<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

How can I change the color of AlertDialog title and the color of the line under it

If you don't want a "library" for that, you can use this badly hack:

((ViewGroup)((ViewGroup)getDialog().getWindow().getDecorView()).getChildAt(0)) //ie LinearLayout containing all the dialog (title, titleDivider, content)
.getChildAt(1) // ie the view titleDivider
.setBackgroundColor(getResources().getColor(R.color.yourBeautifulColor));

This was tested and work on 4.x; not tested under, but if my memory is good it should work for 2.x and 3.x

How do I show a console output/window in a forms application?

If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application

screenshot of changing the project type.

This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.

Just remember to turn it back off before you deploy the program.

Android getting value from selected radiobutton

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

How to get json key and value in javascript?

//By using jquery json parser    
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);

//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

Array of an unknown length in C#

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

How to access Session variables and set them in javascript?

Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

How to negate specific word in regex?

Unless performance is of utmost concern, it's often easier just to run your results through a second pass, skipping those that match the words you want to negate.

Regular expressions usually mean you're doing scripting or some sort of low-performance task anyway, so find a solution that is easy to read, easy to understand and easy to maintain.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

If you just want to check the value is in Range, use this:

   MIN_VALUE = 1;
   MAX_VALUE = 100;
   $customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

How to set environment variable or system property in spring tests?

All of the answers here currently only talk about the system properties which are different from the environment variables that are more complex to set, esp. for tests. Thankfully, below class can be used for that and the class docs has good examples

EnvironmentVariables.html

A quick example from the docs, modified to work with @SpringBootTest

@SpringBootTest
public class EnvironmentVariablesTest {
   @ClassRule
   public final EnvironmentVariables environmentVariables = new EnvironmentVariables().set("name", "value");

   @Test
   public void test() {
     assertEquals("value", System.getenv("name"));
   }
 }

How to run function in AngularJS controller on document ready?

I had a similar situation where I needed to execute a controller function after the view was loaded and also after a particular 3rd-party component within the view was loaded, initialized, and had placed a reference to itself on $scope. What ended up working for me was to setup a watch on this scope property and firing my function only after it was initialized.

// $scope.myGrid property will be created by the grid itself
// The grid will have a loadedRows property once initialized

$scope.$watch('myGrid', function(newValue, oldValue) {
    if (newValue && newValue.loadedRows && !oldValue) {
        initializeAllTheGridThings();
    }
});

The watcher is called a couple of times with undefined values. Then when the grid is created and has the expected property, the initialization function may be safely called. The first time the watcher is called with a non-undefined newValue, oldValue will still be undefined.

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

How to set environment variable for everyone under my linux system?

man 8 pam_env

man 5 pam_env.conf

If all login services use PAM, and all login services have session required pam_env.so in their respective /etc/pam.d/* configuration files, then all login sessions will have some environment variables set as specified in pam_env's configuration file.

On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf.

This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).

I want to show all tables that have specified column name

Pretty simple on a per database level

Use DatabaseName
Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'

How to get duplicate items from a list using LINQ?

Here is one way to do it:

List<String> duplicates = lst.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

The GroupBy groups the elements that are the same together, and the Where filters out those that only appear once, leaving you with only the duplicates.

Get file name from URL

How about this:

String filenameWithoutExtension = null;
String fullname = new File(
    new URI("http://www.xyz.com/some/deep/path/to/abc.png").getPath()).getName();

int lastIndexOfDot = fullname.lastIndexOf('.');
filenameWithoutExtension = fullname.substring(0, 
    lastIndexOfDot == -1 ? fullname.length() : lastIndexOfDot);

"No backupset selected to be restored" SQL Server 2012

I have run into the same issue. Run SSMS as administrator then right click and do database restore. Should work.

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

What are the options to clone or copy a list in Python?

In Python 3, a shallow copy can be made with:

a_copy = a_list.copy()

In Python 2 and 3, you can get a shallow copy with a full slice of the original:

a_copy = a_list[:]

Explanation

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing new equivalent objects.

Shallow list copy

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

Python 2

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

Python 3

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()

In Python 3.5:

>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

Making another pointer does not make a copy

Using new_list = my_list then modifies new_list every time my_list changes. Why is this?

my_list is just a name that points to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

Deep copies

To make a deep copy of a list, in Python 2 or 3, use deepcopy in the copy module:

import copy
a_deep_copy = copy.deepcopy(a_list)

To demonstrate how this allows us to make new sub-lists:

>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

Don't use eval

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  1. It's dangerous, particularly if you're evaluating something from a source you don't trust.
  2. It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
  3. It's also less performant.

In 64 bit Python 2.7:

>>> import timeit
>>> import copy
>>> l = range(10)
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
27.55826997756958
>>> min(timeit.repeat(lambda: eval(repr(l))))
29.04534101486206

on 64 bit Python 3.5:

>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

Replacing last character in a String with java

To get the required result you can do following:

fieldName = fieldName.trim();
fieldName = fieldName.substring(0,fieldName.length() - 1);

How to find tags with only certain attributes - BeautifulSoup

As explained on the BeautifulSoup documentation

You may use this :

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

EDIT :

To return tags that have only the valign="top" attribute, you can check for the length of the tag attrs property :

from BeautifulSoup import BeautifulSoup

html = '<td valign="top">.....</td>\
        <td width="580" valign="top">.......</td>\
        <td>.....</td>'

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

for result in results :
    if len(result.attrs) == 1 :
        print result

That returns :

<td valign="top">.....</td>

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How can I count the number of children?

You can use .length, like this:

var count = $("ul li").length;

.length tells how many matches the selector found, so this counts how many <li> under <ul> elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other <ul> elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li".

In other situations where you don't know the child type, you can use the * (wildcard) selector, or .children(), like this:

var count = $(".parentSelector > *").length;

or:

var count = $(".parentSelector").children().length;

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

Addition for BigDecimal

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);

How to check the version before installing a package using apt-get?

Also, the apt-show-versions package (installed separately) parses dpkg information about what is installed and tells you if packages are up to date.

Example..

$ sudo apt-show-versions --regex chrome
google-chrome-stable/stable upgradeable from 32.0.1700.102-1 to 35.0.1916.114-1
xserver-xorg-video-openchrome/quantal-security uptodate 1:0.3.1-0ubuntu1.12.10.1
$

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

How to open local files in Swagger-UI

In a local directory that contains the file ./docs/specs/openapi.yml that you want to view, you can run the following to start a container and access the spec at http://127.0.0.1:8246.

docker run -t -i -p 8246:8080 -e SWAGGER_JSON=/var/specs/openapi.yml -v $PWD/docs/specs:/var/specs swaggerapi/swagger-ui

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

How to pass multiple parameters to a get method in ASP.NET Core

You also can use this:

// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
    return $"{firstName}:{lastName}:{address}";
}

Note: Please refer to metalheart's and metalheart and Mark Hughes for a possibly better approach.

React - changing an uncontrolled input

When you use onChange={this.onFieldChange('name').bind(this)} in your input you must declare your state empty string as a value of property field.

incorrect way:

this.state ={
       fields: {},
       errors: {},
       disabled : false
    }

correct way:

this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

.NET Format a string with fixed spaces

try this:

"String goes here".PadLeft(20,' ');
"String goes here".PadRight(20,' ');

for the center get the length of the string and do padleft and padright with the necessary characters

int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Does JavaScript have a built in stringbuilder class?

That code looks like the route you want to take with a few changes.

You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this so you can chain your appends.

StringBuilder.prototype.append = function (value) {
    if (value || value === 0) {
        this.strings.push(value);
    }
    return this;
}

Simple Deadlock Examples

If method1() and method2() both will be called by two or many threads, there is a good chance of deadlock because if thread 1 acquires lock on String object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further, which will never happen.

public void method1() {
    synchronized (String.class) {
        System.out.println("Acquired lock on String.class object");

        synchronized (Integer.class) {
            System.out.println("Acquired lock on Integer.class object");
        }
    }
}

public void method2() {
    synchronized (Integer.class) {
        System.out.println("Acquired lock on Integer.class object");

        synchronized (String.class) {
            System.out.println("Acquired lock on String.class object");
        }
    }
}

Custom Listview Adapter with filter Android

You can implement search filter in listview by two ways. 1. using searchview 2. using edittext.

  1. If yo want to use searchview then read here : searchview filter.

  2. If you want to use edittext, read below.

I have taken reference from : listview search filter android

Code snippets to make filter with edittext.

First create model class MovieNames.java:

public class MovieNames {
    private String movieName;

    public MovieNames(String movieName) {
        this.movieName = movieName;
    }

    public String getMovieName() {
        return this.movieName;
    }

}

Create listview_item.xml file :

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Make ListViewAdapter.java class :

    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables

    Context mContext;
    LayoutInflater inflater;
    private ArrayList<MovieNames> arraylist;

    public ListViewAdapter(Context context, ArrayList<MovieNames> arraylist) {
        mContext = context;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = arraylist;

    }

    public class ViewHolder {
        TextView name;
    }

    @Override
    public int getCount() {
        return arraylist.size();
    }

    @Override
    public MovieNames getItem(int position) {
        return arraylist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.listview_item, null);
            // Locate the TextViews in listview_item.xml
            holder.name = (TextView) view.findViewById(R.id.name);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.name.setText(arraylist.get(position).getMovieName());
        return view;
    }


} 

Prepare activity_main.xml file :

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.parsaniahardik.searchedit.MainActivity"
    android:orientation="vertical">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="enter query"
        android:singleLine="true">


        <requestFocus/>
    </EditText>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:divider="#694fea"
        android:dividerHeight="1dp" />


</LinearLayout>

Finally make MainActivity.java class :

    import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText etsearch;
    private ListView list;
    private ListViewAdapter adapter;
    private String[] moviewList;
    public static ArrayList<MovieNames> movieNamesArrayList;
    public static ArrayList<MovieNames> array_sort;
    int textlength = 0;

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

        // Generate sample data

        moviewList = new String[]{"Xmen", "Titanic", "Captain America",
                "Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book",
                "Tarzan","Cars","Shreck"};

        list = (ListView) findViewById(R.id.listView);

        movieNamesArrayList = new ArrayList<>();
        array_sort = new ArrayList<>();

        for (int i = 0; i < moviewList.length; i++) {
            MovieNames movieNames = new MovieNames(moviewList[i]);
            // Binds all strings into an array
            movieNamesArrayList.add(movieNames);
            array_sort.add(movieNames);
        }

        adapter = new ListViewAdapter(this,movieNamesArrayList);
        list.setAdapter(adapter);


        etsearch = (EditText) findViewById(R.id.editText);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, array_sort.get(position).getMovieName(), Toast.LENGTH_SHORT).show();
            }
        });

        etsearch.addTextChangedListener(new TextWatcher() {


            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textlength = etsearch.getText().length();
                array_sort.clear();
                for (int i = 0; i < movieNamesArrayList.size(); i++) {
                    if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) {
                        Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim());
                        if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains(
                                etsearch.getText().toString().toLowerCase().trim())) {
                            array_sort.add(movieNamesArrayList.get(i));
                        }
                    }
                }
                    adapter = new ListViewAdapter(MainActivity.this, array_sort);
                    list.setAdapter(adapter);

            }
        });

    }
}

How do I call one constructor from another in Java?

The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.

Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.

Setter methods or constructors

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

How can I specify a [DllImport] path at runtime?

Contrary to the suggestions by some of the other answers, using the DllImport attribute is still the correct approach.

I honestly don't understand why you can't do just like everyone else in the world and specify a relative path to your DLL. Yes, the path in which your application will be installed differs on different people's computers, but that's basically a universal rule when it comes to deployment. The DllImport mechanism is designed with this in mind.

In fact, it isn't even DllImport that handles it. It's the native Win32 DLL loading rules that govern things, regardless of whether you're using the handy managed wrappers (the P/Invoke marshaller just calls LoadLibrary). Those rules are enumerated in great detail here, but the important ones are excerpted here:

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
  • If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL.

If SafeDllSearchMode is enabled (the default), the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So, unless you're naming your DLL the same thing as a system DLL (which you should obviously not be doing, ever, under any circumstances), the default search order will start looking in the directory from which your application was loaded. If you place the DLL there during the install, it will be found. All of the complicated problems go away if you just use relative paths.

Just write:

[DllImport("MyAppDll.dll")] // relative path; just give the DLL's name
static extern bool MyGreatFunction(int myFirstParam, int mySecondParam);

But if that doesn't work for whatever reason, and you need to force the application to look in a different directory for the DLL, you can modify the default search path using the SetDllDirectory function.
Note that, as per the documentation:

After calling SetDllDirectory, the standard DLL search path is:

  1. The directory from which the application loaded.
  2. The directory specified by the lpPathName parameter.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

So as long as you call this function before you call the function imported from the DLL for the first time, you can modify the default search path used to locate DLLs. The benefit, of course, is that you can pass a dynamic value to this function that is computed at run-time. That isn't possible with the DllImport attribute, so you will still use a relative path (the name of the DLL only) there, and rely on the new search order to find it for you.

You'll have to P/Invoke this function. The declaration looks like this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

What do all of Scala's symbolic operators mean?

Just adding to the other excellent answers. Scala offers two often criticized symbolic operators, /: (foldLeft) and :\ (foldRight) operators, the first being right-associative. So the following three statements are the equivalent:

( 1 to 100 ).foldLeft( 0, _+_ )
( 1 to 100 )./:( 0 )( _+_ )
( 0 /: ( 1 to 100 ) )( _+_ )

As are these three:

( 1 to 100 ).foldRight( 0, _+_ )
( 1 to 100 ).:\( 0 )( _+_ )
( ( 1 to 100 ) :\ 0 )( _+_ )

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

JavaScript string and number conversion

To convert a string to a number, subtract 0. To convert a number to a string, add "" (the empty string).

5 + 1 will give you 6

(5 + "") + 1 will give you "51"

("5" - 0) + 1 will give you 6

Do you have to put Task.Run in a method to make it async?

One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.

private Task<int> DoWorkAsync()
{
    //create a task completion source
    //the type of the result value must be the same
    //as the type in the returning Task
    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
    Task.Run(() =>
    {
        int result = 1 + 2;
        //set the result to TaskCompletionSource
        tcs.SetResult(result);
    });
    //return the Task
    return tcs.Task;
}

private async void DoWork()
{
    int result = await DoWorkAsync();
}

Apache giving 403 forbidden errors

Check that :

  • Apache can physically access the file (the user that run apache, probably www-data or apache, can access the file in the filesystem)
  • Apache can list the content of the folder (read permission)
  • Apache has a "Allow" directive for that folder. There should be one for /var/www/, you can check default vhost for example.

Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log) which will describe why you get the 403 error exactly.

Finally, you may want to restart apache, just to be sure all that configuration is applied. This can be generally done with /etc/init.d/apache2 restart. On some system, the script will be called httpd. Just figure out.

Query grants for a table in postgres

\z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

How do I use JDK 7 on Mac OSX?

As of April 27th there is an offical Oracle release of Java SE 7u4. Download the disk image and run the installer - then see the Mac readme.

JavaScript: filter() for Objects

Solution in Vanilla JS from year 2020.


let romNumbers={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}

You can filter romNumbers object by key:

const filteredByKey = Object.fromEntries(
    Object.entries(romNumbers).filter(([key, value]) => key === 'I') )
// filteredByKey = {I: 1} 

Or filter romNumbers object by value:

 const filteredByValue = Object.fromEntries(
    Object.entries(romNumbers).filter(([key, value]) => value === 5) )
 // filteredByValue = {V: 5} 

How to create own dynamic type or dynamic object in C#?

dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() => 
{ 
    return 55; 
});
Console.WriteLine(MyDynamic.MyMethod());

Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.

How do I check whether a checkbox is checked in jQuery?

You can use:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

Both of them should work.

How do search engines deal with AngularJS applications?

I have found an elegant solution that would cover most of your bases. I wrote about it initially here and answered another similar StackOverflow question here which references it.

FYI this solution also includes hardcoded fallback tags in case Javascript isn't picked up by the crawler. I haven't explicitly outlined it, but it is worth mentioning that you should be activating HTML5 mode for proper URL support.

Also note: these aren't the complete files, just the important parts of those that are relevant. If you need help writing the boilerplate for directives, services, etc. that can be found elsewhere. Anyway, here goes...

app.js

This is where you provide the custom metadata for each of your routes (title, description, etc.)

$routeProvider
   .when('/', {
       templateUrl: 'views/homepage.html',
       controller: 'HomepageCtrl',
       metadata: {
           title: 'The Base Page Title',
           description: 'The Base Page Description' }
   })
   .when('/about', {
       templateUrl: 'views/about.html',
       controller: 'AboutCtrl',
       metadata: {
           title: 'The About Page Title',
           description: 'The About Page Description' }
   })

metadata-service.js (service)

Sets the custom metadata options or use defaults as fallbacks.

var self = this;

// Set custom options or use provided fallback (default) options
self.loadMetadata = function(metadata) {
  self.title = document.title = metadata.title || 'Fallback Title';
  self.description = metadata.description || 'Fallback Description';
  self.url = metadata.url || $location.absUrl();
  self.image = metadata.image || 'fallbackimage.jpg';
  self.ogpType = metadata.ogpType || 'website';
  self.twitterCard = metadata.twitterCard || 'summary_large_image';
  self.twitterSite = metadata.twitterSite || '@fallback_handle';
};

// Route change handler, sets the route's defined metadata
$rootScope.$on('$routeChangeSuccess', function (event, newRoute) {
  self.loadMetadata(newRoute.metadata);
});

metaproperty.js (directive)

Packages the metadata service results for the view.

return {
  restrict: 'A',
  scope: {
    metaproperty: '@'
  },
  link: function postLink(scope, element, attrs) {
    scope.default = element.attr('content');
    scope.metadata = metadataService;

    // Watch for metadata changes and set content
    scope.$watch('metadata', function (newVal, oldVal) {
      setContent(newVal);
    }, true);

    // Set the content attribute with new metadataService value or back to the default
    function setContent(metadata) {
      var content = metadata[scope.metaproperty] || scope.default;
      element.attr('content', content);
    }

    setContent(scope.metadata);
  }
};

index.html

Complete with the hardcoded fallback tags mentioned earlier, for crawlers that can't pick up any Javascript.

<head>
  <title>Fallback Title</title>
  <meta name="description" metaproperty="description" content="Fallback Description">

  <!-- Open Graph Protocol Tags -->
  <meta property="og:url" content="fallbackurl.com" metaproperty="url">
  <meta property="og:title" content="Fallback Title" metaproperty="title">
  <meta property="og:description" content="Fallback Description" metaproperty="description">
  <meta property="og:type" content="website" metaproperty="ogpType">
  <meta property="og:image" content="fallbackimage.jpg" metaproperty="image">

  <!-- Twitter Card Tags -->
  <meta name="twitter:card" content="summary_large_image" metaproperty="twitterCard">
  <meta name="twitter:title" content="Fallback Title" metaproperty="title">
  <meta name="twitter:description" content="Fallback Description" metaproperty="description">
  <meta name="twitter:site" content="@fallback_handle" metaproperty="twitterSite">
  <meta name="twitter:image:src" content="fallbackimage.jpg" metaproperty="image">
</head>

This should help dramatically with most search engine use cases. If you want fully dynamic rendering for social network crawlers (which are iffy on Javascript support), you'll still have to use one of the pre-rendering services mentioned in some of the other answers.

Hope this helps!

How to find good looking font color if background color is known?

If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV

Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees:

h = (h + 180) % 360;

For saturation and value, invert them:

l = 1.0 - l;
v = 1.0 - v;

Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.

If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference

def q(x):
    return x*x
def diff(col1, col2):
    return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b))

and use that.

Fixed position but relative to container

This is easy (as per HTML below)

The trick is to NOT use top or left on the element (div) with "position: fixed;". If these are not specified, the "fixed content" element will appear RELATIVE to the enclosing element (the div with "position:relative;") INSTEAD OF relative to the browser window!!!

<div id="divTermsOfUse" style="width:870px; z-index: 20; overflow:auto;">
    <div id="divCloser" style="position:relative; left: 852px;">
        <div style="position:fixed; z-index:22;">
            <a href="javascript:hideDiv('divTermsOfUse');">
                <span style="font-size:18pt; font-weight:bold;">X</span>
            </a>
        </div>
    </div>
    <div>  <!-- container for... -->
         lots of Text To Be Scrolled vertically...
         bhah! blah! blah!
    </div>
</div>

Above allowed me to locate a closing "X" button at the top of a lot of text in a div with vertical scrolling. The "X" sits in place (does not move with scrolled text and yet it does move left or right with the enclosing div container when the user resizes the width of the browser window! Thus it is "fixed" vertically, but positioned relative to the enclosing element horizontally!

Before I got this working the "X" scrolled up and out of sight when I scrolled the text content down.

Apologies for not providing my javascript hideDiv() function, but it would needlessly make this post longer. I opted to keep it as short as possible.

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Executing Shell Scripts from the OS X Dock?

You could create a Automator workflow with a single step - "Run Shell Script"

Then File > Save As, and change the File Format to "Application". When you open the application, it will run the Shell Script step, executing the command, exiting after it completes.

The benefit to this is it's really simple to do, and you can very easily get user input (say, selecting a bunch of files), then pass it to the input of the shell script (either to stdin, or as arguments).

(Automator is in your /Applications folder!)

Example workflow

Remove HTML Tags from an NSString on the iPhone

Here's the swift version :

func stripHTMLFromString(string: String) -> String {
  var copy = string
  while let range = copy.rangeOfString("<[^>]+>", options: .RegularExpressionSearch) {
    copy = copy.stringByReplacingCharactersInRange(range, withString: "")
  }
  copy = copy.stringByReplacingOccurrencesOfString("&nbsp;", withString: " ")
  copy = copy.stringByReplacingOccurrencesOfString("&amp;", withString: "&")
  return copy
}

Call An Asynchronous Javascript Function Synchronously

Async functions, a feature in ES2017, make async code look sync by using promises (a particular form of async code) and the await keyword. Also notice in the code examples below the keyword async in front of the function keyword that signifies an async/await function. The await keyword won't work without being in a function pre-fixed with the async keyword. Since currently there is no exception to this that means no top level awaits will work (top level awaits meaning an await outside of any function). Though there is a proposal for top-level await.

ES2017 was ratified (i.e. finalized) as the standard for JavaScript on June 27th, 2017. Async await may already work in your browser, but if not you can still use the functionality using a javascript transpiler like babel or traceur. Chrome 55 has full support of async functions. So if you have a newer browser you may be able to try out the code below.

See kangax's es2017 compatibility table for browser compatibility.

Here's an example async await function called doAsync which takes three one second pauses and prints the time difference after each pause from the start time:

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
async function doAsync () {_x000D_
  var start = Date.now(), time;_x000D_
  console.log(0);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
}_x000D_
_x000D_
doAsync();
_x000D_
_x000D_
_x000D_

When the await keyword is placed before a promise value (in this case the promise value is the value returned by the function doSomethingAsync) the await keyword will pause execution of the function call, but it won't pause any other functions and it will continue executing other code until the promise resolves. After the promise resolves it will unwrap the value of the promise and you can think of the await and promise expression as now being replaced by that unwrapped value.

So, since await just pauses waits for then unwraps a value before executing the rest of the line you can use it in for loops and inside function calls like in the below example which collects time differences awaited in an array and prints out the array.

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this calls each promise returning function one after the other_x000D_
async function doAsync () {_x000D_
  var response = [];_x000D_
  var start = Date.now();_x000D_
  // each index is a promise returning function_x000D_
  var promiseFuncs= [doSomethingAsync, doSomethingAsync, doSomethingAsync];_x000D_
  for(var i = 0; i < promiseFuncs.length; ++i) {_x000D_
    var promiseFunc = promiseFuncs[i];_x000D_
    response.push(await promiseFunc() - start);_x000D_
    console.log(response);_x000D_
  }_x000D_
  // do something with response which is an array of values that were from resolved promises._x000D_
  return response_x000D_
}_x000D_
_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

The async function itself returns a promise so you can use that as a promise with chaining like I do above or within another async await function.

The function above would wait for each response before sending another request if you would like to send the requests concurrently you can use Promise.all.

_x000D_
_x000D_
// no change_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
// no change_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this function calls the async promise returning functions all at around the same time_x000D_
async function doAsync () {_x000D_
  var start = Date.now();_x000D_
  // we are now using promise all to await all promises to settle_x000D_
  var responses = await Promise.all([doSomethingAsync(), doSomethingAsync(), doSomethingAsync()]);_x000D_
  return responses.map(x=>x-start);_x000D_
}_x000D_
_x000D_
// no change_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

If the promise possibly rejects you can wrap it in a try catch or skip the try catch and let the error propagate to the async/await functions catch call. You should be careful not to leave promise errors unhandled especially in Node.js. Below are some examples that show off how errors work.

_x000D_
_x000D_
function timeoutReject (time) {_x000D_
  return new Promise(function (resolve, reject) {_x000D_
    setTimeout(function () {_x000D_
      reject(new Error("OOPS well you got an error at TIMESTAMP: " + Date.now()));_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doErrorAsync () {_x000D_
  return timeoutReject(1000);_x000D_
}_x000D_
_x000D_
var log = (...args)=>console.log(...args);_x000D_
var logErr = (...args)=>console.error(...args);_x000D_
_x000D_
async function unpropogatedError () {_x000D_
  // promise is not awaited or returned so it does not propogate the error_x000D_
  doErrorAsync();_x000D_
  return "finished unpropogatedError successfully";_x000D_
}_x000D_
_x000D_
unpropogatedError().then(log).catch(logErr)_x000D_
_x000D_
async function handledError () {_x000D_
  var start = Date.now();_x000D_
  try {_x000D_
    console.log((await doErrorAsync()) - start);_x000D_
    console.log("past error");_x000D_
  } catch (e) {_x000D_
    console.log("in catch we handled the error");_x000D_
  }_x000D_
  _x000D_
  return "finished handledError successfully";_x000D_
}_x000D_
_x000D_
handledError().then(log).catch(logErr)_x000D_
_x000D_
// example of how error propogates to chained catch method_x000D_
async function propogatedError () {_x000D_
  var start = Date.now();_x000D_
  var time = await doErrorAsync() - start;_x000D_
  console.log(time - start);_x000D_
  return "finished propogatedError successfully";_x000D_
}_x000D_
_x000D_
// this is what prints propogatedError's error._x000D_
propogatedError().then(log).catch(logErr)
_x000D_
_x000D_
_x000D_

If you go here you can see the finished proposals for upcoming ECMAScript versions.

An alternative to this that can be used with just ES2015 (ES6) is to use a special function which wraps a generator function. Generator functions have a yield keyword which may be used to replicate the await keyword with a surrounding function. The yield keyword and generator function are a lot more general purpose and can do many more things then just what the async await function does. If you want a generator function wrapper that can be used to replicate async await I would check out co.js. By the way co's function much like async await functions return a promise. Honestly though at this point browser compatibility is about the same for both generator functions and async functions so if you just want the async await functionality you should use Async functions without co.js.

Browser support is actually pretty good now for Async functions (as of 2017) in all major current browsers (Chrome, Safari, and Edge) except IE.

Python: Finding differences between elements of a list

The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:

v = numpy.diff(t)

Get list from pandas DataFrame column headers

This gives us the names of columns in a list:

list(my_dataframe.columns)

Another function called tolist() can be used too:

my_dataframe.columns.tolist()

phpMyAdmin - config.inc.php configuration?

I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php is calling config-db.php

** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1

/etc/phpmyadmin/config-db.php:

$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';

Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration. That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs

How to make an AJAX call without jQuery?

Using the following snippet you can do similar things pretty easily, like this:

ajax.get('/test.php', {foo: 'bar'}, function() {});

Here is the snippet:

var ajax = {};
ajax.x = function () {
    if (typeof XMLHttpRequest !== 'undefined') {
        return new XMLHttpRequest();
    }
    var versions = [
        "MSXML2.XmlHttp.6.0",
        "MSXML2.XmlHttp.5.0",
        "MSXML2.XmlHttp.4.0",
        "MSXML2.XmlHttp.3.0",
        "MSXML2.XmlHttp.2.0",
        "Microsoft.XmlHttp"
    ];

    var xhr;
    for (var i = 0; i < versions.length; i++) {
        try {
            xhr = new ActiveXObject(versions[i]);
            break;
        } catch (e) {
        }
    }
    return xhr;
};

ajax.send = function (url, callback, method, data, async) {
    if (async === undefined) {
        async = true;
    }
    var x = ajax.x();
    x.open(method, url, async);
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            callback(x.responseText)
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.send(data)
};

ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};

ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};

Using a custom typeface in Android

I found a nice solution on the blog of Lisa Wray. With the new data binding it is possible to set the font in your XML files.

@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
    textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}

In XML:

<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

EDIT: dialog support was added to JavaFX, see https://stackoverflow.com/a/28887273/1054140


There were no common dialog support in a year 2011. You had to write it yourself by creating new Stage():

Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);

VBox vbox = new VBox(new Text("Hi"), new Button("Ok."));
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(15));

dialogStage.setScene(new Scene(vbox));
dialogStage.show();

How to prevent downloading images and video files from my website?

You can set the image to be background image and have a transparent foreground image.

Spark Kill Running Application

First use:

yarn application -list

Note down the application id Then to kill use:

yarn application -kill application_id

Create a menu Bar in WPF?

Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):

<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
    <MenuItem Header="_Emulator">
    <MenuItem Header="Load..." Click="MenuItem_Click" />
    <MenuItem Header="Load again" Click="menuEmulLoadLast" />
    <Separator />
    <MenuItem Click="MenuItem_Click">
        <MenuItem.Header>
            <DockPanel>
                <TextBlock>Step</TextBlock>
                <TextBlock Width="10"></TextBlock>
                <TextBlock HorizontalAlignment="Right">F2</TextBlock>
            </DockPanel>
        </MenuItem.Header>
    </MenuItem>
    :

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

For those who are having this issue through a VS client side once successfully added a service reference and trying to execute the first call got this exception: “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel” If you are using (like my case) an endpoint URL with the IP address and got this exception, then you should probably need to re-add the service reference doing this steps:

  • Open the endpoint URL on Internet Explorer.
  • Click on the certificate error (red icon in address bar)
  • Click on View certificates.
  • Grab the issued to: "name" and replace the IP address or whatever name we were using and getting the error for this "name".

Try again :). Thanks

Jquery Ajax Posting json to webservice

I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({

    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {
        alert(errMsg);
    }
});

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Here is a similar solution which I think is more efficient in building up the list of %s strings in the SQL:

Use the list_of_ids directly:

format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
                tuple(list_of_ids))

That way you avoid having to quote yourself, and avoid all kinds of sql injection.

Note that the data (list_of_ids) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.

How to set Google Chrome in WebDriver

I'm using this since the begin and it always work. =)

System.setProperty("webdriver.chrome.driver", "C:\\pathto\\my\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");

PHP: Split string

to explode with '.' use

explode('\\.','a.b');

jQuery bind to Paste Event, how to get the content of the paste

Another approach: That input event will catch also the paste event.

$('textarea').bind('input', function () {
    setTimeout(function () { 
        console.log('input event handled including paste event');
    }, 0);
});

Is there an easy way to add a border to the top and bottom of an Android View?

You can also use a 9-path to do your job. Create it so that colored pixel do not multiply in height but only the transparent pixel.

php resize image on upload

This thing worked for me. No any external liabraries used

    define ("MAX_SIZE","3000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["image-1"]["name"];
    $uploadedfile = $_FILES['image-1']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['image-1']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {
            echo "Unknown Extension..!";
        }
        else
        {

 $size=filesize($_FILES['image-1']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    echo "File Size Excedeed..!!";
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}

list($width,$height)=getimagesize($uploadedfile);


$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];

$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];



imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}

How to deny access to a file in .htaccess

I don't believe the currently accepted answer is correct. For example, I have the following .htaccess file in the root of a virtual server (apache 2.4):

<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>

This prevents external access to reminder.php which is in a subdirectory. I have a similar .htaccess file on my Apache 2.2 server with the same effect:

<Files "reminder.php">
        Order Deny,Allow
        Deny from all
        Allow from localhost
        Allow from 127.0.0.1
     Allow from xxx.yyy.zzz.aaa
</Files>

I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess file, viz <Files ./inscription/log.txt> which is causing it to fail. It would be simpler to put the .htaccess file in the same directory as log.txt i.e. in the inscription directory and it will work there.

Is it possible to get an Excel document's row count without loading the entire document into memory?

Adding on to what Hubro said, apparently get_highest_row() has been deprecated. Using the max_row and max_column properties returns the row and column count. For example:

    wb = load_workbook(path, use_iterators=True)
    sheet = wb.worksheets[0]

    row_count = sheet.max_row
    column_count = sheet.max_column

Prevent flicker on webkit-transition of webkit-transform

Add this css property to the element being flickered:

-webkit-transform-style: preserve-3d;

(And a big thanks to Nathan Hoad: http://nathanhoad.net/how-to-stop-css-animation-flicker-in-webkit)

Why is "npm install" really slow?

install nvm and try it should help, use below command:-

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

What's "this" in JavaScript onclick?

this referes to the object the onclick method belongs to. So inside func this would be the DOM node of the a element and this.innerText would be here.

Find the host name and port using PSQL commands

From the terminal you can simply do a "postgres list clusters":

pg_lsclusters

It will return Postgres version number, cluster names, ports, status, owner, and the location of your data directories and log file.

Adding images to an HTML document with javascript

Get rid of the this statements too

var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)

How to check if type is Boolean

You can use pure Javascript to achieve this:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

jQuery set radio button

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);

Find p-value (significance) in scikit-learn LinearRegression

The code in elyase's answer https://stackoverflow.com/a/27928411/4240413 does not actually work. Notice that sse is a scalar, and then it tries to iterate through it. The following code is a modified version. Not amazingly clean, but I think it works more or less.

class LinearRegression(linear_model.LinearRegression):

    def __init__(self,*args,**kwargs):
        # *args is the list of arguments that might go into the LinearRegression object
        # that we don't know about and don't want to have to deal with. Similarly, **kwargs
        # is a dictionary of key words and values that might also need to go into the orginal
        # LinearRegression object. We put *args and **kwargs so that we don't have to look
        # these up and write them down explicitly here. Nice and easy.

        if not "fit_intercept" in kwargs:
            kwargs['fit_intercept'] = False

        super(LinearRegression,self).__init__(*args,**kwargs)

    # Adding in t-statistics for the coefficients.
    def fit(self,x,y):
        # This takes in numpy arrays (not matrices). Also assumes you are leaving out the column
        # of constants.

        # Not totally sure what 'super' does here and why you redefine self...
        self = super(LinearRegression, self).fit(x,y)
        n, k = x.shape
        yHat = np.matrix(self.predict(x)).T

        # Change X and Y into numpy matricies. x also has a column of ones added to it.
        x = np.hstack((np.ones((n,1)),np.matrix(x)))
        y = np.matrix(y).T

        # Degrees of freedom.
        df = float(n-k-1)

        # Sample variance.     
        sse = np.sum(np.square(yHat - y),axis=0)
        self.sampleVariance = sse/df

        # Sample variance for x.
        self.sampleVarianceX = x.T*x

        # Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root.  ugly)
        self.covarianceMatrix = sc.linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)

        # Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
        self.se = self.covarianceMatrix.diagonal()[1:]

        # T statistic for each beta.
        self.betasTStat = np.zeros(len(self.se))
        for i in xrange(len(self.se)):
            self.betasTStat[i] = self.coef_[0,i]/self.se[i]

        # P-value for each beta. This is a two sided t-test, since the betas can be 
        # positive or negative.
        self.betasPValue = 1 - t.cdf(abs(self.betasTStat),df)

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){
    this.name=name;
  },
  print: function(){
    console.log(this.name);
  }
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

How can I trim beginning and ending double quotes from a string?

To remove the first character and last character from the string, use:

myString = myString.substring(1, myString.length()-1);

How can I group by date time column without taking time into consideration

CAST datetime field to date

select  CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);

How do you create a remote Git branch?

If you have used --single-branch to clone the current branch, use this to create a new branch from the current:

git checkout -b <new-branch-name>
git push -u origin <new-branch-name>
git remote set-branches origin --add <new-branch-name>
git fetch

How does setTimeout work in Node.JS?

setTimeout(callback,t) is used to run callback after at least t millisecond. The actual delay depends on many external factors like OS timer granularity and system load.

So, there is a possibility that it will be called slightly after the set time, but will never be called before.

A timer can't span more than 24.8 days.

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

How to import a csv file using python with headers intact, where first column is a non-numerical

For Python 3

Remove the rb argument and use either r or don't pass argument (default read mode).

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

For Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.

What happens if you don't commit a transaction to a database (say, SQL Server)?

Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.

Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).

How do I convert a String to an int in Java?

Converting a string to an int is more complicated than just converting a number. You have think about the following issues:

  • Does the string only contain numbers 0-9?
  • What's up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
  • What's up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

Get source jar files attached to Eclipse for Maven-managed dependencies

If you are using meclipse do

window --> maven --> Download Artifact Sources (select check)

(If you still get attach source window, then click on attach file button and close the attach source window. The next time you try to see the source it will open the correct source)

Surajz

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

Swift 3

extension Date {
    
    func toString(template: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
        return formatter.string(from: self)
    }
    
}

Usage

let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09

Play with template to match your needs. Examples and doc here to help you build the template you need.

Note

You may want to cache your DateFormatter if you plan to use it in TableView for instance. To give an idea, looping over 1000 dates took me 0.5 sec using the above toString(template: String) function, compared to 0.05 sec using myFormatter.string(from: Date).

Ways to save enums in database

I would argue that the only safe mechanism here is to use the String name() value. When writing to the DB, you could use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without "imposing" this on the DB.

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to add a TextView to a LinearLayout dynamically in Android?

LayoutParams lparams = new LayoutParams(
   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);

You can change lparams according to your needs

Visibility of global variables in imported modules

A function uses the globals of the module it's defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.

A better solution: don't use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.

Bridged networking not working in Virtualbox under Windows 10

Virtual Box gives a lot of issues when it comes to bridge adaptor. I had the same issue with Virtual Box for windows 10. I decided to create VirtualBox Host-Only Ethernet adapter. But I again got issues while creating the host-only ethernet adaptor. I decided to switch to vmware. Vmware did not give me any issues. After installing vmware (and after changing few settings in the BIOS) and installing ubuntu on it, it automatically connected to my host machine's internet. It was able to generate it's own IP address as well and could also ping the host machine (windows machine). Hence, for me virtual box created a lot of issues whereas, vmware worked smoothly for me.

Get current directory name (without full path) in a Bash script

For the find jockeys out there like me:

find $PWD -maxdepth 0 -printf "%f\n"

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

Auto insert date and time in form input field?

See the example, http://jsbin.com/ahehe

Use the JavaScript date formatting utility described here.

<input id="date" name="date" />

<script>
   document.getElementById('date').value = (new Date()).format("m/dd/yy");
</script>

How to build minified and uncompressed bundle with webpack?

You can create two configs for webpack, one that minifies the code and one that doesn't (just remove the optimize.UglifyJSPlugin line) and then run both configurations at the same time $ webpack && webpack --config webpack.config.min.js

How to avoid using Select in Excel VBA

The main reason never to use Select or Activesheet is because most people will have at least another couple of workbooks open (sometimes dozens) when they run your macro, and if they click away from your sheet while your macro is running and click on some other book they have open, then the "Activesheet" changes, and the target workbook for an unqualified "Select" command changes as well.

At best, your macro will crash, at worst you might end up writing values or changing cells in the wrong workbook with no way to "Undo" them.

I have a simple golden rule that I follow: Add variables named "wb" and "ws" for a Workbook object and a Worksheet object and always use those to refer to my macro book. If I need to refer to more than one book, or more than one sheet, I add more variables.

For example,

Dim wb as Workbook
Dim ws as Worksheet
Set wb = ThisWorkBook
Set ws = wb.sheets("Output")

The "Set wb = ThisWorkbook" command is absolutely key. "ThisWorkbook" is a special value in Excel, and it means the workbook that your VBA code is currently running from. A very helpful shortcut to set your Workbook variable with.

After you've done that at the top of your Sub, using them could not be simpler, just use them wherever you would use "Selection":

So to change the value of cell "A1" in "Output" to "Hello", instead of:

Sheets("Output").Activate
ActiveSheet.Range("A1").Select
Selection.Value = "Hello"

We can now do this:

ws.Range("A1").Value = "Hello"

Which is not only much more reliable and less likely to crash if the user is working with multiple spreadsheets; it's also much shorter, quicker and easier to write.

As an added bonus, if you always name your variables "wb" and "ws", you can copy and paste code from one book to another and it will usually work with minimal changes needed, if any.

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

Subtract 1 day with PHP

Not sure why your current code isn't working but if you don't specifically need a date object this will work:

$first_date = strtotime($date_raw);
$second_date = strtotime('-1 day', $first_date);

print 'First Date ' . date('Y-m-d', $first_date);
print 'Next Date ' . date('Y-m-d', $second_date);

How to connect to my http://localhost web server from Android Emulator

I used 10.0.2.2 successfully on my home machine, but at work, it did not work. After hours of fooling around, I created a new emulator instance using the Android Virtual Device (AVD) manager, and finally the 10.0.2.2 worked.

I don't know what was wrong with the other emulator instance (the platform was the same), but if you find 10.0.2.2 does not work, try creating a new emulator instance.

What is the difference between syntax and semantics in programming languages?

Semantics is what your code means--what you might describe in pseudo-code. Syntax is the actual structure--everything from variable names to semi-colons.

Django: Redirect to previous page after login

To support full urls with param/values you'd need:

?next={{ request.get_full_path|urlencode }}

instead of just:

?next={{ request.path }}

MongoDB or CouchDB - fit for production?

Adobe is using MongoDB for their upcoming release of Adobe Experience Manager (formerly Day CQ) as the core DB engine.

Several client's at the agency I work at are using CouchDB on projects for large clients.

Both are great and viable DBs, in my opinion. :)

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

jQuery removeClass wildcard

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

In case you're an extension developer who googled your way here trying to stop causing this error:

The issue isn't CORB (as another answer here states) as blocked CORs manifest as warnings like -

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.example.com/example.html with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

The issue is most likely a mishandled async response to runtime.sendMessage. As MDN says:

To send an asynchronous response, there are two options:

  • return true from the event listener. This keeps the sendResponse function valid after the listener returns, so you can call it later.
  • return a Promise from the event listener, and resolve when you have the response (or reject it in case of an error).

When you send an async response but fail to use either of these mechanisms, the supplied sendResponse argument to sendMessage goes out of scope and the result is exactly as the error message says: your message port (the message-passing apparatus) is closed before the response was received.

Webextension-polyfill authors have already written about it in June 2018.

So bottom line, if you see your extension causing these errors - inspect closely all your onMessage listeners. Some of them probably need to start returning promises (marking them as async should be enough). [Thanks @vdegenne]

How can I create directory tree in C++/Linux?

mkdir -p /dir/to/the/file

touch /dir/to/the/file/thefile.ending

Can Windows Containers be hosted on linux?

You can use Windows Containers inside a virtual machine (the guest OS should match the requirements - Windows 10 Pro or Windows 2016).

For example you can use VirtualBox, just enable Hyper-V inside System / Acceleration / Paravirtualization Interface.

After that if Docker doesn't start up because of an error, use the "Switch to Windows containers..." in the settings.

(this could be moved as a comment to the accepted answer, but I don't have enough reputation to do so)

What is the common header format of Python files?

The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:

  • The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
  • The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.
  • And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

How to initialize java.util.date to empty

IMO, you cannot create an empty Date(java.util). You can create a Date object with null value and can put a null check.

 Date date = new Date(); // Today's date and current time
 Date date2 = new Date(0); // Default date and time
 Date date3 = null; //Date object with null as value.
 if(null != date3) {
    // do your work.
 }

Responsive image align center bootstrap 3

The more exact way applied to all Booostrap objects using standard classes only would be to not set top and bottom margins (as image can inherit these from parent), so I am always using:

.text-center .img-responsive {
    margin-left: auto;
    margin-right: auto;
}

I have also made a Gist for that, so if any changes will apply because of any bugs, update version will be always here: https://gist.github.com/jdrda/09a38bf152dd6a8aff4151c58679cc66

x86 Assembly on a Mac

Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows

On Windows its:

mov $source , %destination

but on the Mac its the other way around.

How to populate/instantiate a C# array with a single value?

If you're planning to only set a few of the values in the array, but want to get the (custom) default value most of the time, you could try something like this:

public class SparseArray<T>
{
    private Dictionary<int, T> values = new Dictionary<int, T>();

    private T defaultValue;

    public SparseArray(T defaultValue)
    {
        this.defaultValue = defaultValue;
    }

    public T this [int index]
    {
      set { values[index] = value; }
      get { return values.ContainsKey(index) ? values[index] ? defaultValue; }
    }
}

You'll probably need to implement other interfaces to make it useful, such as those on array itself.

Converting double to integer in Java

Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);

Solved my purpose.

Difference between static memory allocation and dynamic memory allocation

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

How to use SharedPreferences in Android to store, fetch and edit values

Basic idea of SharedPreferences is to store things on XML file.

  1. Declare your xml file path.(if you don't have this file, Android will create it. If you have this file, Android will access it.)

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    
  2. Write value to Shared Preferences

    prefs.edit().putLong("preference_file_key", 1010101).apply();
    

    the preference_file_key is the name of shared preference files. And the 1010101 is the value you need to store.

    apply() at last is to save the changes. If you get error from apply(), change it to commit(). So this alternative sentence is

    prefs.edit().putLong("preference_file_key", 1010101).commit();
    
  3. Read from Shared Preferences

    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    

    lsp will be -1 if preference_file_key has no value. If 'preference_file_key' has a value, it will return the value of this.

The whole code for writing is

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    prefs.edit().putLong("preference_file_key", 1010101).apply();    // Write the value to key.

The code for reading is

    SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    long lsp = sp.getLong("preference_file_key", -1);    // Read the key and store in lsp

Split page vertically using CSS

I guess your elements on the page messes up because you don't clear out your floats, check this out

Demo

HTML

<div class="wrap">
    <div class="floatleft"></div>
    <div class="floatright"></div>
    <div style="clear: both;"></div>
</div>

CSS

.wrap {
    width: 100%;
}

.floatleft {
    float:left; 
    width: 80%;
    background-color: #ff0000;
    height: 400px;
}

.floatright {
float: right;
    background-color: #00ff00;
    height: 400px;
    width: 20%;
}

How do I tell what type of value is in a Perl variable?

A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.

If you want to know if it is a reference, you can use ref. If you want to know the reference type, you can use the reftype routine from Scalar::Util.

If you want to know if it is an object, you can use the blessed routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL has some methods to tell you about an object: if you want to check that it has the method you want to call, use can; if you want to see that it inherits from something, use isa; and if you want to see it the object handles a role, use DOES.

If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied. If you get an object, continue your checks.

If you want to know if it looks like a number, you can use looks_like_number from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.

If you need to do something more fancy, you can use a module such as Params::Validate.

Why does this CSS margin-top style not work?

Try using display: inline-block; on the inner div.

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:block;
}
#inner {
    background:#FFCC33;
    margin:50px 50px 50px 50px;
    padding:10px;
    display:inline-block;
}

python: get directory two levels up

You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.

from pathlib import Path

p = Path(__file__).parents[1]

print(p)
# /absolute/path/to/two/levels/up

This uses the parents sequence which provides access to the parent directories and chooses the 2nd one up.

Note that p in this case will be some form of Path object, with their own methods. If you need the paths as string then you can call str on them.

How to list files in a directory in a C program?

Below code will only print files within directory and exclude directories within given directory while traversing.

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    char path[1000]="/home/joy/Downloads";
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Condition to check regular file.
            if(dir->d_type==DT_REG){
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("%s\n",full_path);
            }
        }
        closedir(d);
    }
    return(0);     
}

Integrate ZXing in Android Studio

From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.

Add the following to your build.gradle file:

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
}

android {
    buildToolsVersion '28.0.3' // Older versions may give compile errors
}

Older SDK versions

For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:

repositories {
    jcenter()
}

dependencies {
    implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.zxing:core:3.3.0'
}

android {
    buildToolsVersion '28.0.3'
}

You'll also need this in your Android manifest:

<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />

Source : https://github.com/journeyapps/zxing-android-embedded

Use table row coloring for cells in Bootstrap

With less you can set it up like this;

.table tbody tr {
    &.error > td { background-color: red !important; }
    &.error:hover > td { background-color: yellow !important; }
    &.success > td { background-color: green !important; }
    &.success:hover > td { background-color: yellow !important; }
    ...
}

That did the trick for me.

How to merge every two lines into one from the command line?

You can also use the following vi command:

:%g/.*/j