Programs & Examples On #Interix

Interix is a POSIX conformant add-on for the Microsoft Windows operating systems.

Add space between <li> elements

Most answers here are not correct as they would add bottom space to the last <li> as well, so they are not adding space ONLY in between <li> !

The most accurate and efficient solution is the following:

li.menu-item:not(:last-child) { 
   margin-bottom: 3px;  
}

Explanation: by using :not(:last-child) the style will be applie to all items (li.menu-item) but the last one.

Boolean vs tinyint(1) for boolean values in MySQL

Whenever you choose int or bool it matters especially when nullable column comes into play.

Imagine a product with multiple photos. How do you know which photo serves as a product cover? Well, we would use a column that indicates it.

So far out product_image table has two columns: product_id and is_cover

Cool? Not yet. Since the product can have only one cover we need to add a unique index on these two columns.

But wait, if these two column will get an unique index how would you store many non-cover images for the same product? The unique index would throw an error here.

So you may though "Okay, but you can use NULL value since these are ommited by unique index checks", and yes this is truth, but we are loosing linguistic rules here.

What is the purpose of NULL value in boolean type column? Is it "all", "any", or "no"? The null value in boolean column allows us to use the unique index, but it also messes up how we interpret the records.

I would tell that in some cases the integer can serve a better purpose since its not bound to strict true or false meaning

Error: Argument is not a function, got undefined

Some times this error is a result of two ng-app directives specified in the html. In my case by mistake I had specified ng-app in my html tag and ng-app="myApp" in the body tag like this:

<html ng-app>
  <body ng-app="myApp"></body>
</html>

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

The reason why this happened to me was that a remote server was allowing only certain IP addressed but not its own, and I was trying to render the images from the server's URLs... so everything would simply halt, displaying the timeout error that you had...

Make sure that either the server is allowing its own IP, or that you are rendering things from some remote URL that actually exists.

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

How can I install Visual Studio Code extensions offline?

If you are looking for a scripted solution:

  1. Get binary download URL: you can use an API, but be warned that there is no documentation for it. This API can return an URL to download .vsix files (see example below)
  2. Download the binary
  3. Carefully unzip the binary into ~/.vscode/extensions/: you need to modify unzipped directory name, remove one file and move/rename another one.

For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.

POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json

{
    "filters": [
        {
        "criteria": [
            {
                "filterType": 8,
                "value": "Microsoft.VisualStudio.Code",
            },
            {
                "filterType": 7,
                "value": "ms-python.python",
            }
        ],
        "pageNumber": 1,
        "pageSize": 10,
        "sortBy": 0,
        "sortOrder": 0,
        }
    ],
    "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
    "flags": 514,
}

Explanations to the above example:

  • "filterType": 8 - FilterType.Target more FilterTypes
  • "filterType": 7 - FilterType.ExtensionName more FilterTypes
  • "flags": 514 - 0x2 | 0x200 - Flags.IncludeFiles | Flags.IncludeLatestVersionOnly - more Flags
    • to get flag decimal value you can run python -c "print(0x2|0x200)"
  • "assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"] - to get only link to .vsix file more AssetTypes

Popup Message boxes

Use the following library: import javax.swing.JOptionPane;

Input at the top of the code-line. You must only add this, because the other things is done correctly!

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

Understanding INADDR_ANY for socket programming

INADDR_ANY instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0"). For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to :: address for IPv6 socket.

#include <netinet/in.h>

struct in6_addr addr = IN6ADDR_ANY_INIT;

Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Basically <key>ITSAppUsesNonExemptEncryption</key><false/> stands for a Boolean value equal to NO.

info.plist value

Update by @JosepH: This value means that the app uses no encryption, or only exempt encryption. If your app uses encryption and is not exempt, you must set this value to YES/true.

It seems debatable sometimes when an app is considered to use encryption.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to convert currentTimeMillis to a date in Java?

The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

Count the number occurrences of a character in a string

count is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda, something like this :

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This will result in :

4

Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in. Have a look :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This also results in :

4

But Of-course this will work only when checking occurrence of single character such as 'a' in this particular case.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Editing in the Chrome debugger

This is what you are looking for:

1.- Navigate to the Source tab and open the javascript file

2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.

In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.

More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/

MySQL: ALTER TABLE if column not exists

Add field if not exist:

CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');

addFieldIfNotExists code:

DELIMITER $$

DROP PROCEDURE IF EXISTS addFieldIfNotExists 
$$

DROP FUNCTION IF EXISTS isFieldExisting 
$$

CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100)) 
RETURNS INT
RETURN (
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.columns 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = table_name_IN 
    AND COLUMN_NAME = field_name_IN
)
$$

CREATE PROCEDURE addFieldIfNotExists (
    IN table_name_IN VARCHAR(100)
    , IN field_name_IN VARCHAR(100)
    , IN field_definition_IN VARCHAR(100)
)
BEGIN

    SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
    IF (@isFieldThere = 0) THEN

        SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
        SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);

        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END IF;

END;
$$

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank


¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

Occurrences of substring in a string

here is the other solution without using regexp/patterns/matchers or even not using StringUtils.

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

ASP.NET MVC ActionLink and post method

Use the following the Call the Action Link:

<%= Html.ActionLink("Click Here" , "ActionName","ContorllerName" )%>

For submitting the form values use:

 <% using (Html.BeginForm("CustomerSearchResults", "Customer"))
   { %>
      <input type="text" id="Name" />
      <input type="submit" class="dASButton" value="Submit" />
   <% } %>

It will submit the Data to Customer Controller and CustomerSearchResults Action.

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.

There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.

Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.

Meaning of - <?xml version="1.0" encoding="utf-8"?>

The XML declaration in the document map consists of the following:

The version number, ?xml version="1.0"?. 

This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.

The encoding declaration,

encoding="UTF-8"?

This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.

How do I integrate Ajax with Django applications?

Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax

Usage:

<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />

Finally, include this in the HEAD of your html:

$('a').bjax();

For more settings, checkout demo here: Bjax Demo

Datetime in where clause

Use a convert function to get all entries for a particular day.

Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'

See CAST and CONVERT for more info

ECMAScript 6 class destructor

You have to manually "destruct" objects in JS. Creating a destroy function is common in JS. In other languages this might be called free, release, dispose, close, etc. In my experience though it tends to be destroy which will unhook internal references, events and possibly propagates destroy calls to child objects as well.

WeakMaps are largely useless as they cannot be iterated and this probably wont be available until ECMA 7 if at all. All WeakMaps let you do is have invisible properties detached from the object itself except for lookup by the object reference and GC so that they don't disturb it. This can be useful for caching, extending and dealing with plurality but it doesn't really help with memory management for observables and observers. WeakSet is a subset of WeakMap (like a WeakMap with a default value of boolean true).

There are various arguments on whether to use various implementations of weak references for this or destructors. Both have potential problems and destructors are more limited.

Destructors are actually potentially useless for observers/listeners as well because typically the listener will hold references to the observer either directly or indirectly. A destructor only really works in a proxy fashion without weak references. If your Observer is really just a proxy taking something else's Listeners and putting them on an observable then it can do something there but this sort of thing is rarely useful. Destructors are more for IO related things or doing things outside of the scope of containment (IE, linking up two instances that it created).

The specific case that I started looking into this for is because I have class A instance that takes class B in the constructor, then creates class C instance which listens to B. I always keep the B instance around somewhere high above. A I sometimes throw away, create new ones, create many, etc. In this situation a Destructor would actually work for me but with a nasty side effect that in the parent if I passed the C instance around but removed all A references then the C and B binding would be broken (C has the ground removed from beneath it).

In JS having no automatic solution is painful but I don't think it's easily solvable. Consider these classes (pseudo):

function Filter(stream) {
    stream.on('data', function() {
        this.emit('data', data.toString().replace('somenoise', '')); // Pretend chunks/multibyte are not a problem.
    });
}
Filter.prototype.__proto__ = EventEmitter.prototype;
function View(df, stream) {
    df.on('data', function(data) {
        stream.write(data.toUpper()); // Shout.
    });
}

On a side note, it's hard to make things work without anonymous/unique functions which will be covered later.

In a normal case instantiation would be as so (pseudo):

var df = new Filter(stdin),
    v1 = new View(df, stdout),
    v2 = new View(df, stderr);

To GC these normally you would set them to null but it wont work because they've created a tree with stdin at the root. This is basically what event systems do. You give a parent to a child, the child adds itself to the parent and then may or may not maintain a reference to the parent. A tree is a simple example but in reality you may also find yourself with complex graphs albeit rarely.

In this case, Filter adds a reference to itself to stdin in the form of an anonymous function which indirectly references Filter by scope. Scope references are something to be aware of and that can be quite complex. A powerful GC can do some interesting things to carve away at items in scope variables but that's another topic. What is critical to understand is that when you create an anonymous function and add it to something as a listener to ab observable, the observable will maintain a reference to the function and anything the function references in the scopes above it (that it was defined in) will also be maintained. The views do the same but after the execution of their constructors the children do not maintain a reference to their parents.

If I set any or all of the vars declared above to null it isn't going to make a difference to anything (similarly when it finished that "main" scope). They will still be active and pipe data from stdin to stdout and stderr.

If I set them all to null it would be impossible to have them removed or GCed without clearing out the events on stdin or setting stdin to null (assuming it can be freed like this). You basically have a memory leak that way with in effect orphaned objects if the rest of the code needs stdin and has other important events on it prohibiting you from doing the aforementioned.

To get rid of df, v1 and v2 I need to call a destroy method on each of them. In terms of implementation this means that both the Filter and View methods need to keep the reference to the anonymous listener function they create as well as the observable and pass that to removeListener.

On a side note, alternatively you can have an obserable that returns an index to keep track of listeners so that you can add prototyped functions which at least to my understanding should be much better on performance and memory. You still have to keep track of the returned identifier though and pass your object to ensure that the listener is bound to it when called.

A destroy function adds several pains. First is that I would have to call it and free the reference:

df.destroy();
v1.destroy();
v2.destroy();
df = v1 = v2 = null;

This is a minor annoyance as it's a bit more code but that is not the real problem. When I hand these references around to many objects. In this case when exactly do you call destroy? You cannot simply hand these off to other objects. You'll end up with chains of destroys and manual implementation of tracking either through program flow or some other means. You can't fire and forget.

An example of this kind of problem is if I decide that View will also call destroy on df when it is destroyed. If v2 is still around destroying df will break it so destroy cannot simply be relayed to df. Instead when v1 takes df to use it, it would need to then tell df it is used which would raise some counter or similar to df. df's destroy function would decrease than counter and only actually destroy if it is 0. This sort of thing adds a lot of complexity and adds a lot that can go wrong the most obvious of which is destroying something while there is still a reference around somewhere that will be used and circular references (at this point it's no longer a case of managing a counter but a map of referencing objects). When you're thinking of implementing your own reference counters, MM and so on in JS then it's probably deficient.

If WeakSets were iterable, this could be used:

function Observable() {
    this.events = {open: new WeakSet(), close: new WeakSet()};
}
Observable.prototype.on = function(type, f) {
    this.events[type].add(f);
};
Observable.prototype.emit = function(type, ...args) {
    this.events[type].forEach(f => f(...args));
};
Observable.prototype.off = function(type, f) {
    this.events[type].delete(f);
};

In this case the owning class must also keep a token reference to f otherwise it will go poof.

If Observable were used instead of EventListener then memory management would be automatic in regards to the event listeners.

Instead of calling destroy on each object this would be enough to fully remove them:

df = v1 = v2 = null;

If you didn't set df to null it would still exist but v1 and v2 would automatically be unhooked.

There are two problems with this approach however.

Problem one is that it adds a new complexity. Sometimes people do not actually want this behaviour. I could create a very large chain of objects linked to each other by events rather than containment (references in constructor scopes or object properties). Eventually a tree and I would only have to pass around the root and worry about that. Freeing the root would conveniently free the entire thing. Both behaviours depending on coding style, etc are useful and when creating reusable objects it's going to be hard to either know what people want, what they have done, what you have done and a pain to work around what has been done. If I use Observable instead of EventListener then either df will need to reference v1 and v2 or I'll have to pass them all if I want to transfer ownership of the reference to something else out of scope. A weak reference like thing would mitigate the problem a little by transferring control from Observable to an observer but would not solve it entirely (and needs check on every emit or event on itself). This problem can be fixed I suppose if the behaviour only applies to isolated graphs which would complicate the GC severely and would not apply to cases where there are references outside the graph that are in practice noops (only consume CPU cycles, no changes made).

Problem two is that either it is unpredictable in certain cases or forces the JS engine to traverse the GC graph for those objects on demand which can have a horrific performance impact (although if it is clever it can avoid doing it per member by doing it per WeakMap loop instead). The GC may never run if memory usage does not reach a certain threshold and the object with its events wont be removed. If I set v1 to null it may still relay to stdout forever. Even if it does get GCed this will be arbitrary, it may continue to relay to stdout for any amount of time (1 lines, 10 lines, 2.5 lines, etc).

The reason WeakMap gets away with not caring about the GC when non-iterable is that to access an object you have to have a reference to it anyway so either it hasn't been GCed or hasn't been added to the map.

I am not sure what I think about this kind of thing. You're sort of breaking memory management to fix it with the iterable WeakMap approach. Problem two can also exist for destructors as well.

All of this invokes several levels of hell so I would suggest to try to work around it with good program design, good practices, avoiding certain things, etc. It can be frustrating in JS however because of how flexible it is in certain aspects and because it is more naturally asynchronous and event based with heavy inversion of control.

There is one other solution that is fairly elegant but again still has some potentially serious hangups. If you have a class that extends an observable class you can override the event functions. Add your events to other observables only when events are added to yourself. When all events are removed from you then remove your events from children. You can also make a class to extend your observable class to do this for you. Such a class could provide hooks for empty and non-empty so in a since you would be Observing yourself. This approach isn't bad but also has hangups. There is a complexity increase as well as performance decrease. You'll have to keep a reference to object you observe. Critically, it also will not work for leaves but at least the intermediates will self destruct if you destroy the leaf. It's like chaining destroy but hidden behind calls that you already have to chain. A large performance problem is with this however is that you may have to reinitialise internal data from the Observable everytime your class becomes active. If this process takes a very long time then you might be in trouble.

If you could iterate WeakMap then you could perhaps combine things (switch to Weak when no events, Strong when events) but all that is really doing is putting the performance problem on someone else.

There are also immediate annoyances with iterable WeakMap when it comes to behaviour. I mentioned briefly before about functions having scope references and carving. If I instantiate a child that in the constructor that hooks the listener 'console.log(param)' to parent and fails to persist the parent then when I remove all references to the child it could be freed entirely as the anonymous function added to the parent references nothing from within the child. This leaves the question of what to do about parent.weakmap.add(child, (param) => console.log(param)). To my knowledge the key is weak but not the value so weakmap.add(object, object) is persistent. This is something I need to reevaluate though. To me that looks like a memory leak if I dispose all other object references but I suspect in reality it manages that basically by seeing it as a circular reference. Either the anonymous function maintains an implicit reference to objects resulting from parent scopes for consistency wasting a lot of memory or you have behaviour varying based on circumstances which is hard to predict or manage. I think the former is actually impossible. In the latter case if I have a method on a class that simply takes an object and adds console.log it would be freed when I clear the references to the class even if I returned the function and maintained a reference. To be fair this particular scenario is rarely needed legitimately but eventually someone will find an angle and will be asking for a HalfWeakMap which is iterable (free on key and value refs released) but that is unpredictable as well (obj = null magically ending IO, f = null magically ending IO, both doable at incredible distances).

Remove last characters from a string in C#. An elegant way?

This will return to you a string excluding everything after the comma

str = str.Substring(0, str.IndexOf(','));

Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:

commaPos = str.IndexOf(',');
if(commaPos != -1)
    str = str.Substring(0, commaPos)

I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:

myInt = (int)double.Parse(myString)

This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.

Is there a better way to do optional function parameters in JavaScript?

Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...

/**
 * Updates an object's properties with other objects' properties. All
 * additional non-falsy arguments will have their properties copied to the
 * destination object, in the order given.
 */
function extend(dest) {
  for (var i = 1, l = arguments.length; i < l; i++) {
    var src = arguments[i]
    if (!src) {
      continue
    }
    for (var property in src) {
      if (src.hasOwnProperty(property)) {
        dest[property] = src[property]
      }
    }
  }
  return dest
}

/**
 * Inherit another function's prototype without invoking the function.
 */
function inherits(child, parent) {
  var F = function() {}
  F.prototype = parent.prototype
  child.prototype = new F()
  child.prototype.constructor = child
  return child
}

...this can be made a bit nicer.

function Field(kwargs) {
  kwargs = extend({
    required: true, widget: null, label: null, initial: null,
    helpText: null, errorMessages: null
  }, kwargs)
  this.required = kwargs.required
  this.label = kwargs.label
  this.initial = kwargs.initial
  // ...and so on...
}

function CharField(kwargs) {
  kwargs = extend({
    maxLength: null, minLength: null
  }, kwargs)
  this.maxLength = kwargs.maxLength
  this.minLength = kwargs.minLength
  Field.call(this, kwargs)
}
inherits(CharField, Field)

What's nice about this method?

  • You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass undefined when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.
  • When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when CharField calls Field's constructor).
  • Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will always be used.

Regex for quoted string with escaping quotes

If it is searched from the beginning, maybe this can work?

\"((\\\")|[^\\])*\"

Java - No enclosing instance of type Foo is accessible

Thing is an inner class with an automatic connection to an instance of Hello. You get a compile error because there is no instance of Hello for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:

static class Thing

Spring Boot yaml configuration for a list of strings

@Value("${your.elements}")    
private String[] elements;

yml file:

your:
 elements: element1, element2, element3

How can I create an MSI setup?

You can use Wix (which is free) to create an MSI installation package.

WiX Tutorial - Creating an Installer MSI with Wix

CSS ''background-color" attribute not working on checkbox inside <div>

Improving another answer here

input[type=checkbox] {
  cursor: pointer;
  margin-right: 10px;
}

input[type=checkbox]:after {
  content: " ";
  background-color: lightgray;
  display: inline-block;
  position: relative;
  top: -4px;
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

input[type=checkbox]:checked:after {
  content: "\00a0\2714";
}

Can I apply multiple background colors with CSS3?

Yes its possible! and you can use as many colors and images as you desire, here is the right way:

_x000D_
_x000D_
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image:  _x000D_
/* 1) An image              */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient              */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position        */ 0 0, _x000D_
/* 2) Gradient position     */ 0 100px,_x000D_
/* 3) Color position        */ 0 130px;_x000D_
_x000D_
background-size:  _x000D_
/* 1) Image size            */ 640px 100px,_x000D_
/* 2) Gradient size         */ 100% 30px, _x000D_
/* 3) Color size            */ 100% 30px;_x000D_
}
_x000D_
_x000D_
_x000D_

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

Visualizing branch topology in Git

I usually use

git log --graph --full-history --all --pretty=format:"%h%x09%d%x20%s"

With colors (if your shell is Bash):

git log --graph --full-history --all --color \
        --pretty=format:"%x1b[31m%h%x09%x1b[32m%d%x1b[0m%x20%s"

This will print text-based representation like this:

* 040cc7c       (HEAD, master) Manual is NOT built by default
* a29ceb7       Removed offensive binary file that was compiled on my machine and was hence incompatible with other machines.
| * 901c7dd     (cvc3) cvc3 now configured before building
| * d9e8b5e     More sane Yices SMT solver caller
| | * 5b98a10   (nullvars) All uninitialized variables get zero inits
| |/
| * 1cad874     CFLAGS for cvc3 to work successfully
| *   1579581   Merge branch 'llvm-inv' into cvc3
| |\
| | * a9a246b   nostaticalias option
| | * 73b91cc   Comment about aliases.
| | * 001b20a   Prints number of iteration and node.
| |/
|/|
| * 39d2638     Included header files to cvc3 sources
| * 266023b     Added cvc3 to blast infrastructure.
| * ac9eb10     Initial sources of cvc3-1.5
|/
* d642f88       Option -aliasstat, by default stats are suppressed

(You could just use git log --format=oneline, but it will tie commit messages to numbers, which looks less pretty IMHO).

To make a shortcut for this command, you may want to edit your ~/.gitconfig file:

[alias]
  gr = log --graph --full-history --all --color --pretty=tformat:"%x1b[31m%h%x09%x1b[32m%d%x1b[0m%x20%s%x20%x1b[33m(%an)%x1b[0m"

However, as Sodel the Vociferous notes in the comments, such long formatting command is hard to memorize. Usually, it's not a problem as you may put it into the ~/.gitconfig file. However, if you sometimes have to log in to a remote machine where you can't modify the config file, you could use a more simple but faster to type version:

git log --graph --oneline

Check folder size in Bash

Use a summary (-s) and bytes (-b). You can cut the first field of the summary with cut. Putting it all together:

CHECK=$(du -sb /data/sflow_log | cut -f1)

How do you copy the contents of an array to a std::vector in C++ without looping?

There have been many answers here and just about all of them will get the job done.

However there is some misleading advice!

Here are the options:

vector<int> dataVec;

int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
unsigned dataArraySize = sizeof(dataArray) / sizeof(int);

// Method 1: Copy the array to the vector using back_inserter.
{
    copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}

// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve
{
    dataVec.reserve(dataVec.size() + dataArraySize);
    copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));
}

// Method 3: Memcpy
{
    dataVec.resize(dataVec.size() + dataArraySize);
    memcpy(&dataVec[dataVec.size() - dataArraySize], &dataArray[0], dataArraySize * sizeof(int));
}

// Method 4: vector::insert
{
    dataVec.insert(dataVec.end(), &dataArray[0], &dataArray[dataArraySize]);
}

// Method 5: vector + vector
{
    vector<int> dataVec2(&dataArray[0], &dataArray[dataArraySize]);
    dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());
}

To cut a long story short Method 4, using vector::insert, is the best for bsruth's scenario.

Here are some gory details:

Method 1 is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.

Method 2 is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this might help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). Bjarne agrees. Incidentally, I found that this method performed the slowest most of the time though I'm struggling to comprehensively explain why it was regularly significantly slower than method 1...

Method 3 is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can only be used for POD types. I would never use this solution.

Method 4 is the best way to go. It's meaning is clear, it's (usually) the fastest and it works for any objects. There is no downside to using this method for this application.

Method 5 is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast-ish and clear.

Finally, you are aware that you can use vectors in place of arrays, right? Even when a function expects c-style arrays you can use vectors:

vector<char> v(50); // Ensure there's enough space
strcpy(&v[0], "prefer vectors to c arrays");

Hope that helps someone out there!

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

Going to a specific line number using Less in Unix

With n being the line number:

  • ng: Jump to line number n. Default is the start of the file.
  • nG: Jump to line number n. Default is the end of the file.

So to go to line number 320123, you would type 320123g.

Copy-pasted straight from Wikipedia.

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

CSS to select/style first word

An easy way to do with HTML+CSS:

TEXT A <b>text b</b>

<h1>text b</h1>

<style>
    h1 { /* the css style */}
    h1:before {content:"text A (p.e.first word) with different style";    
    display:"inline";/* the different css style */}
</style>

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Table with fixed header and fixed column on pure css

All of these suggestions are great and all, but they're either only fixing either the header or a column, not both, or they're using javascript. The reason - it don't believe it can be done in pure CSS. The reason:

If it were possible to do it, you would need to nest several scrollable divs one inside the other, each with a scroll in a different direction. Then you would need to split your table into three parts - the fixed header, the fixed column and the rest of the data.

Fine. But now the problem - you can make one of them stay put when you scroll, but the other one is nested inside the scrolling area of first and is therefore subject to being scrolled out of sight itself, so can't be fixed in place on the screen. 'Ah-ha' you say 'but I can somehow use absolute or fixed position to do that' - no you can't. As soon as you do that you lose the ability to scroll that container. It's a chicken and egg situation - you can't have both, they cancel each other out.

I believe the only solution is through javascript. You need to completely seperate out the three elements and keep their positions in sync through javascript. There are good examples in other posts on this page. This one is also worth a look:

http://tympanus.net/codrops/2014/01/09/sticky-table-headers-columns/

Getting URL parameter in java and extract a specific text from that URL

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

Import These Libraries

    import java.net.URL;
    import java.util.regex.*;

Copy/Paste this function

    public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)

How to calculate the number of days between two dates?

Here is my implementation:

function daysBetween(one, another) {
  return Math.round(Math.abs((+one) - (+another))/8.64e7);
}

+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.

How do I compile with -Xlint:unchecked?

For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters enter "-Xlint:unchecked".

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

I have a simple example here to display date and time with Millisecond......

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyClass{

    public static void main(String[]args){
        LocalDateTime myObj = LocalDateTime.now();
        DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS);
        String forDate = myObj.format(myFormat);
        System.out.println("The Date and Time are: " + forDate);
    }
}

How to fast-forward a branch to head?

Move your branch pointer to the HEAD:

git branch -f master

Your branch master already exists, so git will not allow you to overwrite it, unless you use... -f (this argument stands for --force)

Or you can use rebase:

git rebase HEAD master

Do it on your own risk ;)

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

CSS - center two images in css side by side

You can't have two elements with the same ID.

Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.

Instead, try something like this:

<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>

CSS:

.link {
    width: 50%;
    float: left;
    text-align: center;
}

Jquery change <p> text programmatically

Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.

<p id="pTest">Male</p>
<button>change</button>

<script>
$('button').click(function(){
     $('#pTest').text('test')
})
</script>

http://jsfiddle.net/CA5Cs/

Remove xticks in a matplotlib plot?

The tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.

from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom=False,      # ticks along the bottom edge are off
    top=False,         # ticks along the top edge are off
    labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()

enter image description here

How to remove specific elements in a numpy array

If you don't know the index, you can't use logical_and

x = 10*np.random.randn(1,100)
low = 5
high = 27
x[0,np.logical_and(x[0,:]>low,x[0,:]<high)]

USB Debugging option greyed out

FYI My Motorola Xyboard had an "Off" icon at the top of developer options. Once I tapped that it worked.

Is there a way to get version from package.json in nodejs code?

For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.

$ genversion lib/version.js

I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Best way to list files in Java, sorted by Date Modified?

You can use Apache LastModifiedFileComparator library

 import org.apache.commons.io.comparator.LastModifiedFileComparator;  


File[] files = directory.listFiles();
        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        for (File file : files) {
            Date lastMod = new Date(file.lastModified());
            System.out.println("File: " + file.getName() + ", Date: " + lastMod + "");
        }

How to delete columns that contain ONLY NAs?

Another option with Filter

Filter(function(x) !all(is.na(x)), df)

NOTE: Data from @Simon O'Hanlon's post.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Microsoft is releasing the "Microsoft Edge WebView2" WPF control that will get us a great, free option for embedding Chromium across Windows 10, Windows 8.1, or Windows 7. It is available via Nuget as the package Microsoft.Web.WebView2.

Best way to add Activity to an Android project in Eclipse?

An easy method suggested by Google Android Developer Community.

enter image description here

What is a daemon thread in Java?

A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the JVM just exits.

    Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.

Html.EditorFor Set Default Value

The clean way to do so is to pass a new instance of the created entity through the controller:

//GET
public ActionResult CreateNewMyEntity(string default_value)
{
    MyEntity newMyEntity = new MyEntity();
    newMyEntity._propertyValue = default_value;

    return View(newMyEntity);
}

If you want to pass the default value through ActionLink

@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

How to calculate number of days between two given dates?

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

This assumes, of course, that you've already verified that your dates are in the format r'\d+/\d+/\d+'.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

.prop('checked',false) or .removeAttr('checked')?

use checked : true, false property of the checkbox.

jQuery:

if($('input[type=checkbox]').is(':checked')) {
    $(this).prop('checked',true);
} else {
    $(this).prop('checked',false);
}

How to iterate over associative arrays in Bash

Use this higher order function to prevent the pyramid of doom

foreach(){ 
  arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=}; 
  for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}

example:

$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

jQuery Show-Hide DIV based on Checkbox Value

A tip to all people that use flat-red, flat-green plugin, because of this plugin the answers above wont work!

In that case, use onchange="do_your_stuff();" on the label, for example: Your checkbox here

The reason why it doesn't work is that this Jquery creates a lot of objects around the real checkbox, so you can't see if it's changed or not.

But if someone click straight on checkbox, won't work :'(

How do I make a burn down chart in Excel?

Why not graph the percentage complete. If you include the last date as a 100% complete value you can force the chart to show the linear trend as well as the actual data. This should give you a reasonable idea of whether you are above or below the line.

I would include a screenshot but not enough rep. Here is a link to one I prepared earlier. Burn Down Chart.

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

You can add this at the beginning after #include <iostream>:

using namespace std;

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

!python 'script.py'

replace script.py with your real file name, DON'T forget ''

Android studio - Failed to find target android-18

What worked for me in Android Studio (0.8.1):

  1. Right click on project name and open Module Settings
  2. Verify SDK Locations SDK
  3. Verify Gradle and Plugin Versions (Review the error message hints for the proper version to use) Gradke
  4. On the app Module set the Compile SDK Version to android-L (latest)
  5. Set the Build Tools version to largest available value (in my case 20.0.0) Build

These changes via the UI make the equivalent changes represented in other answers but is a better way to proceed because on close, all appropriate files (current and future) will be updated automatically (which is helpful when confronted by the many places where issues can occur).

NB: It is very important to review the Event Log and note that Android Studio provides helpful messages on alternative ways to resolve such issues.

How to set java_home on Windows 7?

Find JDK Installation Directory

First you need to know the installation path for the Java Development Kit.

Open the default installation path for the JDK:

C:\Program Files\Java

There should be a subdirectory like:

C:\Program Files\Java\jdk1.8.0_172

Note: one has only to put the path to the jdk without /bin in the end (as suggested on a lot of places). e.g. C:\Java\jdk1.8.0_172 and NOT C:\Java\jdk1.8.0_172\bin !


Set the JAVA_HOME Variable

Once you have the JDK installation path:

  1. Right-click the My Computer icon on your desktop and select Properties.
  2. Click the Advanced tab, then click the Environment Variables button.
  3. Under System Variables, click New.
  4. Enter the variable name as JAVA_HOME.
  5. Enter the variable value as the installation path for the Java Development Kit.
  6. Click OK.
  7. Click Apply Changes.

Note: You might need to restart Windows

The complete article is here, on my blog: Setting JAVA_HOME Variable in Windows.

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Remove blank attributes from an Object in Javascript

Shorter ES6 pure solution, convert it to an array, use the filter function and convert it back to an object. Would also be easy to make a function...

Btw. with this .length > 0 i check if there is an empty string / array, so it will remove empty keys.

const MY_OBJECT = { f: 'te', a: [] }

Object.keys(MY_OBJECT)
 .filter(f => !!MY_OBJECT[f] && MY_OBJECT[f].length > 0)
 .reduce((r, i) => { r[i] = MY_OBJECT[i]; return r; }, {});

JS BIN https://jsbin.com/kugoyinora/edit?js,console

Dropdownlist width in IE

I tried all of these solutions and none worked completely for me. This is what I came up with

$(document).ready(function () {

var clicknum = 0;

$('.dropdown').click(
        function() {
            clicknum++;
            if (clicknum == 2) {
                clicknum = 0;
                $(this).css('position', '');
                $(this).css('width', '');
            }
        }).blur(
        function() {
            $(this).css('position', '');
            $(this).css('width', '');
            clicknum = 0;
        }).focus(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        }).mousedown(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        });
})(jQuery);

Be sure to add a dropdown class to each dropdown in your html

The trick here is using the specialized click function (I found it here Fire event each time a DropDownList item is selected with jQuery). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected.

Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.

You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though

Creating a Plot Window of a Particular Size

Use dev.new(). (See this related question.)

plot(1:10)
dev.new(width=5, height=4)
plot(1:20)

To be more specific which units are used:

dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)

edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)

For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)

Using MySQL with Entity Framework

Vintana,

Od course there's something ready now. http://www.devart.com/products.html - it's commercial although (you have a 30days trial IIRC). They make a living writing providers, so I guess it should be fast and stable. I know really big companies using their Oracle provider instead of Orace and MS ones.

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

How can I limit possible inputs in a HTML5 "number" element?

If you are looking for a Mobile Web solution in which you wish your user to see a number pad rather than a full text keyboard. Use type="tel". It will work with maxlength which saves you from creating extra javascript.

Max and Min will still allow the user to Type in numbers in excess of max and min, which is not optimal.

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

ObjectiveC Parse Integer from String

I really don't know what was so hard about this question, but I managed to do it this way:

[myStringContainingInt intValue];

It should be noted that you can also do:

myStringContainingInt.intValue;

How can I add a space in between two outputs?

+"\n" + can be added in print command to display the code block after it in next line

E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

curl : (1) Protocol https not supported or disabled in libcurl

I just recompiled curl with configure options pointing to the openssl 1.0.2g library folder and include folder, and I still get this message. When I do ldd on curl, it does not show that it uses either libcrypt.so or libssl.so, so I assume this must mean that even though the make and make install succeeded without errors, nevertheless curl does not have HTTPS support? Configure and make was as follows:

./configure --prefix=/local/scratch/PACKAGES/local --with-ssl=/local/scratch/PACKAGES/local/openssl/openssl-1.0.2g --includedir=/local/scratch/PACKAGES/local/include/openssl/openssl-1.0.2g
make
make test
make install

I should mention that libssl.so.1 is in /local/scratch/PACKAGES/local/lib. It is unclear whether the --with-ssl option should point there or to the directory where the openssl install placed the openssl.cnf file. I chose the latter. But if it were supposed to be the former, the make should have failed with an error that it couldn't find the library.

Ruby 'require' error: cannot load such file

require loads a file from the $LOAD_PATH. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH, use require_relative.

Space between two divs

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

How to Set Opacity (Alpha) for View in Android

I know this already has a bunch of answers but I found that for buttons it is just easiest to create your own .xml selectors and set that to the background of said button. That way you can also change it state when pressed or enabled and so on. Here is a quick snippet of one that I use. If you want to add a transparency to any of the colors, add a leading hex value (#XXcccccc). (XX == "alpha of color")

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Can I run javascript before the whole page is loaded?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.

What issues should be considered when overriding equals and hashCode in Java?

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

How to validate numeric values which may contain dots or commas?

\d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

* means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

Putting that all together you can use:

\d{1,2}([\.,][\d{1,2}])?

Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

C compile error: "Variable-sized object may not be initialized"

After declaring the array

int boardAux[length][length];

the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

int i, j;
for (i = 0; i<length; i++)
{
    for (j = 0; j<length; j++)
        boardAux[i][j] = 0;
}

Showing percentages above bars on Excel column graph

Either

  1. Use a line series to show the %
  2. Update the data labels above the bars to link back directly to other cells

Method 2 by step

  • add data-lables
  • right-click the data lable
  • goto the edit bar and type in a refence to a cell (C4 in this example)
  • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

enter image description here

Complex CSS selector for parent of active child

THE “PARENT” SELECTOR

Right now, there is no option to select the parent of an element in CSS (not even CSS3). But with CSS4, the most important news in the current W3C draft is the support for the parent selector.

$ul li:hover{
    background: #fff;
}

Using the above, when hovering an list element, the whole unordered list will be highlighted by adding a white background to it.

Official documentation: https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview (last row).

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

state provider and route provider in angularJS

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

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

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

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

ORA-28000: the account is locked error getting frequently

Login to SQL Plus client on the oracle database server machine.

enter user-name: system

enter password: password [Only if, if you have not changed your default password while DB installation]

press enter. after which, you will be seeing the connection status.

Now,

SQL> ALTER USER [USER_NAME] ACCOUNT UNLOCK;

press enter.

you will be seeing message: user altered.

Now try login with the user name on db client[sqldeveloper].

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

filemtime "warning stat failed for"

I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:

  function deleteOldFiles(){
    if ($handle = opendir('./xml')) {
        while (false !== ($file = readdir($handle))) { 

            if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
              $fpath = 'xml/'.$file;
              if (file_exists($fpath)) {
                $filelastmodified = filemtime($fpath);

                if ( (time() - $filelastmodified ) > 24*3600){
                    unlink($fpath);
                }
              }
            }
        }
        closedir($handle); 
    }
  }

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

After half a day of fiddling with this, found out that PDO had a bug where...

--

//This would run as expected:
$pdo->exec("valid-stmt1; valid-stmt2;");

--

//This would error out, as expected:
$pdo->exec("non-sense; valid-stmt1;");

--

//Here is the bug:
$pdo->exec("valid-stmt1; non-sense; valid-stmt3;");

It would execute the "valid-stmt1;", stop on "non-sense;" and never throw an error. Will not run the "valid-stmt3;", return true and lie that everything ran good.

I would expect it to error out on the "non-sense;" but it doesn't.

Here is where I found this info: Invalid PDO query does not return an error

Here is the bug: https://bugs.php.net/bug.php?id=61613


So, I tried doing this with mysqli and haven't really found any solid answer on how it works so I thought I's just leave it here for those who want to use it..

try{
    // db connection
    $mysqli = new mysqli("host", "user" , "password", "database");
    if($mysqli->connect_errno){
        throw new Exception("Connection Failed: [".$mysqli->connect_errno. "] : ".$mysqli->connect_error );
        exit();
    }

    // read file.
    // This file has multiple sql statements.
    $file_sql = file_get_contents("filename.sql");

    if($file_sql == "null" || empty($file_sql) || strlen($file_sql) <= 0){
        throw new Exception("File is empty. I wont run it..");
    }

    //run the sql file contents through the mysqli's multi_query function.
    // here is where it gets complicated...
    // if the first query has errors, here is where you get it.
    $sqlFileResult = $mysqli->multi_query($file_sql);
    // this returns false only if there are errros on first sql statement, it doesn't care about the rest of the sql statements.

    $sqlCount = 1;
    if( $sqlFileResult == false ){
        throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], [".$mysqli->errno."]: '".$mysqli->error."' }");
    }

    // so handle the errors on the subsequent statements like this.
    // while I have more results. This will start from the second sql statement. The first statement errors are thrown above on the $mysqli->multi_query("SQL"); line
    while($mysqli->more_results()){
        $sqlCount++;
        // load the next result set into mysqli's active buffer. if this fails the $mysqli->error, $mysqli->errno will have appropriate error info.
        if($mysqli->next_result() == false){
            throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], Error No: [".$mysqli->errno."]: '".$mysqli->error."' }");
        }
    }
}
catch(Exception $e){
    echo $e->getMessage(). " <pre>".$e->getTraceAsString()."</pre>";
}

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

Comparing two files in linux terminal

Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.

For example:

mcdiff file1 file2

Enjoy!

How to check if a float value is a whole number

You can use the round function to compute the value.

Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:

def cube_integer(n):
    if round(n**(1.0/3.0))**3 == n:
        return True
    return False

But remember that int(n) is equivalent to math.floor and because of this if you find the int(41063625**(1.0/3.0)) you will get 344 instead of 345.

So please be careful when using int withe cube roots.

Console app arguments, how arguments are passed to Main method

Read MSDN.

it also contains a link to the args.

short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.

if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)

in the main you will need to read those args for example:

for (int i = 0; i < args.Length; i++)
{
    string flag = args.GetValue(i).ToString();
    if (flag == "bla") 
    {
        Bla();
    }
}

How to change an application icon programmatically in Android?

As mentioned before you need use <activity-alias> to change the application icon. To avoid killing the application after enabling appropriate activity-alias you need to do this after the application is killed. To find out if the application was killed you can use this method

  1. Create activity aliases in AndroidManifest.xml
<activity android:name=".ui.MainActivity"/>

<activity-alias
    android:name=".one"
    android:icon="@mipmap/ic_launcher_one"
    android:targetActivity=".ui.MainActivity"
    android:enabled="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>

<activity-alias
    android:name=".two"
    android:icon="@mipmap/ic_launcher_two"
    android:targetActivity=".ui.MainActivity"
    android:enabled="false">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>
  1. ?reate a service that will change the active activity-alias after killing the application. You need store the name of new active activity-alias somewhere (e.g. SharedPreferences)
class ChangeAppIconService: Service() {
    private val aliases = arrayOf(".one", ".two")

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        changeAppIcon()
        stopSelf()
    }

    fun changeAppIcon() {
        val sp = getSharedPreferences("appSettings", Context.MODE_PRIVATE)

        sp.getString("activeActivityAlias", ".one").let { aliasName ->
            if (!isAliasEnabled(aliasName)) {
                setAliasEnabled(aliasName)
            }
        }
    }

    private fun isAliasEnabled(aliasName: String): Boolean {
        return packageManager.getComponentEnabledSetting(
            ComponentName(
                this,
                "${BuildConfig.APPLICATION_ID}$aliasName"
            )
        ) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
    }

    private fun setAliasEnabled(aliasName: String) {
        aliases.forEach {
            val action = if (it == aliasName)
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            else
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
            packageManager.setComponentEnabledSetting(
                ComponentName(
                    this,
                    "${BuildConfig.APPLICATION_ID}$aliasName"
                ),
                action,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}
  1. Add service to AndroidManifest.xml
<service 
    android:name=".ChangeAppIconService"
    android:stopWithTask="false"
    />
  1. Start ChangeAppIconService in MainActivity.onCreate
class MainActivity: Activity {

    ...

    override fun onCreate(savedInstanceState: Bundle?) {
       ...

       startService(Intent(this, ChangeAppIconService::class.java))

       ...
    }

    ...

}

Catching access violation exceptions?

Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.

> man signal

     11    SIGSEGV      create core image    segmentation violation

Writing to a NULL pointer is probably going to cause a SIGSEGV signal

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Position Relative vs Absolute?

Another thing to note is that if you want a absolute element to be confined to a parent element then you need to set the parent element's position to relative. That will keep the child element contained within the parent element and it won't be "relative" to the entire window.

I wrote a blog post that gives a simple example that creates the following affect:

enter image description here

That has a green div that is absolutely positioned to the bottom of the parent yellow div.

1 http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/

Is there an equivalent of lsusb for OS X

If you are a user of MacPorts, you may simply install usbutils

sudo port install usbutils

If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.

Can I mask an input text in a bat file?

I read all the clunky solutions on the net about how to mask passwords in a batch file, the ones from using a hide.com solution and even the ones that make the text and the background the same color. The hide.com solution works decent, it isn't very secure, and it doesn't work in 64-bit Windows. So anyway, using 100% Microsoft utilities, there is a way!

First, let me explain my use. I have about 20 workstations that auto logon to Windows. They have one shortcut on their desktop - to a clinical application. The machines are locked down, they can't right click, they can't do anything but access the one shortcut on their desktop. Sometimes it is necessary for a technician to kick up some debug applications, browse windows explorer and look at log files without logging the autolog user account off.

So here is what I have done.

Do it however you wish, but I put my two batch files on a network share that the locked down computer has access to.

My solution utilizes 1 main component of Windows - runas. Put a shortcut on the clients to the runas.bat you are about to create. FYI, on my clients I renamed the shortcut for better viewing purposes and changed the icon.

You will need to create two batch files.

I named the batch files runas.bat and Debug Support.bat

runas.bat contains the following code:

cls
@echo off
TITLE CHECK CREDENTIALS 
goto menu

:menu
cls
echo.
echo           ....................................
echo            ~Written by Cajun Wonder 4/1/2010~
echo           ....................................
echo.
@set /p un=What is your domain username? 
if "%un%"=="PUT-YOUR-DOMAIN-USERNAME-HERE" goto debugsupport
if not "%un%"=="PUT-YOUR-DOMAIN-USERNAME-HERE" goto noaccess
echo.
:debugsupport
"%SYSTEMROOT%\system32\runas" /netonly /user:PUT-YOUR-DOMAIN-NAME-HERE\%un% "\\PUT-YOUR-NETWORK-SHARE-PATH-HERE\Debug Support.bat"
@echo ACCESS GRANTED! LAUNCHING THE DEBUG UTILITIES....
@ping -n 4 127.0.0.1 > NUL
goto quit
:noaccess
cls
@echo.
@echo.
@echo.
@echo.
@echo   \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
@echo   \\                                   \\
@echo   \\    Insufficient privileges         \\  
@echo   \\                                    \\
@echo   \\      Call Cajun Wonder             \\
@echo   \\                                    \\
@echo   \\              At                    \\
@echo   \\                                    \\
@echo   \\        555-555-5555                \\
@echo   \\                                    \\
@echo   \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
@ping -n 4 127.0.0.1 > NUL
goto quit
@pause
:quit
@exit

You can add as many if "%un%" and if not "%un%" for all the users you want to give access to. The @ping is my coonass way of making a seconds timer.

So that takes care of the first batch file - pretty simple eh?

Here is the code for Debug Support.bat:

cls
@echo off
TITLE SUPPORT UTILITIES
goto menu

:menu
cls
@echo %username%
echo.
echo           .....................................
echo            ~Written by Cajun Wonder 4/1/2010~
echo           .....................................
echo.
echo What do you want to do? 
echo.
echo [1]  Launch notepad
echo.

:choice
set /P C=[Option]? 
if "%C%"=="1" goto notepad
goto choice

:notepad
echo.
@echo starting notepad....
@ping -n 3 127.0.0.1 > NUL
start notepad
cls
goto menu

I'm not a coder and really just started getting into batch scripting about a year ago, and this round about way that I discovered of masking a password in a batch file is pretty awesome!

I hope to hear that someone other than me is able to get some use out of it!

How to add a border to a widget in Flutter?

You can use Container to contain your widget:

Container(
  decoration: BoxDecoration(
    border: Border.all(
    color: Color(0xff000000),
    width: 1,
  )),
  child: Text()
),

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

On OpenSUSE 15.3 systemd log reported this error (insmod suggestion was unhelpful).

Feb 18 08:36:38 vagrant-openSUSE-Leap dockerd[20635]: iptables v1.6.2: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

REBOOT fixed the problem

Alternative to Intersect in MySQL

Microsoft SQL Server's INTERSECT "returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand" This is different from a standard INNER JOIN or WHERE EXISTS query.

SQL Server

CREATE TABLE table_a (
    id INT PRIMARY KEY,
    value VARCHAR(255)
);

CREATE TABLE table_b (
    id INT PRIMARY KEY,
    value VARCHAR(255)
);

INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');

SELECT value FROM table_a
INTERSECT
SELECT value FROM table_b

value
-----
B

(1 rows affected)

MySQL

CREATE TABLE `table_a` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `value` varchar(255),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE `table_b` LIKE `table_a`;

INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');

SELECT value FROM table_a
INNER JOIN table_b
USING (value);

+-------+
| value |
+-------+
| B     |
| B     |
+-------+
2 rows in set (0.00 sec)

SELECT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);

+-------+
| value |
+-------+
| B     |
| B     |
+-------+

With this particular question, the id column is involved, so duplicate values will not be returned, but for the sake of completeness, here's a MySQL alternative using INNER JOIN and DISTINCT:

SELECT DISTINCT value FROM table_a
INNER JOIN table_b
USING (value);

+-------+
| value |
+-------+
| B     |
+-------+

And another example using WHERE ... IN and DISTINCT:

SELECT DISTINCT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);

+-------+
| value |
+-------+
| B     |
+-------+

How to unstash only certain files?

One more way:

git diff stash@{N}^! -- path/to/file1 path/to/file2  | git apply -R

jQuery select element in parent window

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.

How to kill all processes matching a name?

If you're using cygwin or some minimal shell that lacks killall you can just use this script:

killall.sh - Kill by process name.

#/bin/bash
ps -W | grep "$1" | awk '{print $1}' | xargs kill --

Usage:

$ killall <process name>

Random date in C#

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

Regex matching in a Bash if statement

In case someone wanted an example using variables...

#!/bin/bash

# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"

if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
    echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
    echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

Traits vs. interfaces

If you know English and know what trait means, it is exactly what the name says. It is a class-less pack of methods and properties you attach to existing classes by typing use.

Basically, you could compare it to a single variable. Closures functions can use these variables from outside of the scope and that way they have the value inside. They are powerful and can be used in everything. Same happens to traits if they are being used.

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)
{
    if(a==1)
        document.getElementById("asd").style.display="none";
    else
        document.getElementById("asd").style.display="block";
}

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Displaying files (e.g. images) stored in Google Drive on a website

Specifically for G-Suite users . As reported in point 3 here, you can use this URL for hosting image

https://drive.google.com/a/domain.com/thumbnail?id=imageID

with following replacements

  • domain: replace with your company's GSuite domain like pikachu
  • imageID: replace with the image id / file id

The prerequisite here is that image should have been shared via drive to target audience (either with each person individually or maybe across the org)

enter image description here


If you face problems with size of rendered image, use following options as mentioned here

https://drive.google.com/a/domain.com/thumbnail?id=imageID&sz=w{width}-h{height}

with following replacements (in addition to domain and imageID replacement)

  • {width}: write the width in pixels (without braces) like 300
  • {height}: write the height in pixels (without braces) like 200

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Edit your privileges on PHPmyAdmin (WAMP), Note that your password and user name has not been created. So do create or edit it, that it might work with your sql connection in your php. Hope it works

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

Can you style an html radio button to look like a checkbox?

Three years after this question is posted and this is almost within reach. In fact, it's completely achievable in Firefox 1+, Chrome 1+, Safari 3+ and Opera 15+ using the CSS3 appearance property.

The result is radio elements that look like checkboxes:

_x000D_
_x000D_
input[type="radio"] {_x000D_
  -webkit-appearance: checkbox; /* Chrome, Safari, Opera */_x000D_
  -moz-appearance: checkbox;    /* Firefox */_x000D_
  -ms-appearance: checkbox;     /* not currently supported */_x000D_
}
_x000D_
<label><input type="radio" name="radio"> Checkbox 1</label>_x000D_
<label><input type="radio" name="radio"> Checkbox 2</label>
_x000D_
_x000D_
_x000D_ jsfiddle: http://jsfiddle.net/mq8Zq/

Note: this was eventually dropped from the CSS3 specification due to a lack of support and conformance from vendors. I'd recommend against implementing it unless you only need to support Webkit or Gecko based browsers.

Query to get the names of all tables in SQL Server 2008 Database

another way, will also work on MySQL and PostgreSQL

select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'

Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

RepeatingOperation = function(op, yieldEveryIteration) {

  //keeps count of how many times we have run heavytask() 
  //before we need to temporally check back with the browser.
  var count = 0;   

  this.step = function() {

    //Each time we run heavytask(), increment the count. When count
    //is bigger than the yieldEveryIteration limit, pass control back 
    //to browser and instruct the browser to immediately call op() so
    //we can pick up where we left off.  Repeat until we are done.
    if (++count >= yieldEveryIteration) {
      count = 0;

      //pass control back to the browser, and in 1 millisecond, 
      //have the browser call the op() function.  
      setTimeout(function() { op(); }, 1, [])

      //The following return statement halts this thread, it gives 
      //the browser a sigh of relief, your long-running javascript
      //loop has ended (even though technically we havn't yet).
      //The browser decides there is no need to alarm the user of
      //an unresponsive javascript process.
      return;
      }
    op();
  };
};

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

process10000HeavyTasks = function() {
  var len = 10000;  
  for (var i = len - 1; i >= 0; i--) {
    heavytask();   //heavytask() can be run about 20  times before
                   //an 'unresponsive script' dialog appears.
                   //If heavytask() is run more than 20 times in one
                   //javascript thread, the browser informs the user that
                   //an unresponsive script needs to be dealt with.  

                   //This is where we need to terminate this long running
                   //thread, instruct the browser not to panic on an unresponsive
                   //script, and tell it to call us right back to pick up
                   //where we left off.
  }
}

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

process10000HeavyTasks = function() {

  var global_i = 10000; //initialize your 'for loop stepper' (i) here.

  var repeater = new this.RepeatingOperation(function() {

    heavytask();

    if (--global_i >= 0){     //Your for loop conditional goes here.
      repeater.step();        //while we still have items to process,
                              //run the next iteration of the loop.
    }
    else {
       alert("we are done");  //when this line runs, the for loop is complete.
    }
  }, 10);                   //10 means process 10 heavytask(), then
                            //yield back to the browser, and have the
                            //browser call us right back.

  repeater.step();          //this command kicks off the recursive closure.

};

Adapted from this source:

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

How to include (source) R script in other scripts

Here is one possible way. Use the exists function to check for something unique in your util.R code.

For example:

if(!exists("foo", mode="function")) source("util.R")

(Edited to include mode="function", as Gavin Simpson pointed out)

jQuery fade out then fade in

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}

Difference between partition key, composite key and clustering key in Cassandra?

In cassandra , the difference between primary key,partition key,composite key, clustering key always makes some confusion.. So I am going to explain below and co relate to each others. We use CQL (Cassandra Query Language) for Cassandra database access. Note:- Answer is as per updated version of Cassandra. Primary Key :-

In cassandra there are 2 different way to use primary Key .

CREATE TABLE Cass (
    id int PRIMARY KEY,
    name text 
);

Create Table Cass (
   id int,
   name text,
   PRIMARY KEY(id) 
);

In CQL, the order in which columns are defined for the PRIMARY KEY matters. The first column of the key is called the partition key having property that all the rows sharing the same partition key (even across table in fact) are stored on the same physical node. Also, insertion/update/deletion on rows sharing the same partition key for a given table are performed atomically and in isolation. Note that it is possible to have a composite partition key, i.e. a partition key formed of multiple columns, using an extra set of parentheses to define which columns forms the partition key.

Partitioning and Clustering The PRIMARY KEY definition is made up of two parts: the Partition Key and the Clustering Columns. The first part maps to the storage engine row key, while the second is used to group columns in a row.

CREATE TABLE device_check (
  device_id   int,
  checked_at  timestamp,
  is_power    boolean,
  is_locked   boolean,
  PRIMARY KEY (device_id, checked_at)
);

Here device_id is partition key and checked_at is cluster_key.

We can have multiple cluster key as well as partition key too which depends on declaration.

XAMPP - MySQL shutdown unexpectedly

When you're not running XAMPP as an administrator, shutting down MySQL frequently causes corruption which means you have to repair or delete your tables. To avoid this you need to either run XAMPP as an administrator, or use the proper command prompt method for shutting down MySQL.

You can delete ibdata1 as Kratos suggests, but this can leave you with a broken database as other pieces of your database are still in the /mysql/data/ folder. In my case, this residual data stopped me successfully installing WordPress.

A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.

Addendum: To ensure that you don't forget to run XAMPP as an administrator you can right click the XAMPP shortcut, go to Properties, then Advanced, and finally tick Run as administrator.

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

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

The correct solution is a FullText Search (if you can use it) https://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

This nearly does what you want:

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100)+.*(Stylus|2100)+';

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*';

But this will also match "210021002100" which is not great.

Find the least number of coins required that can make any change from 1 to 99 cents

You need at least 4 pennies, since you want to get 4 as a change, and you can do that only with pennies.

It isn't optimal to have more than 4 pennies. Instead of 4+x pennies, you can have 4 pennies and x nickels - they span at least the same range.

So you have exactly 4 pennies.

You need at least 1 nickel, since you want to get 5 as a change.

It isn't optimal to have more than 1 nickel. Instead of 1+x nickels, you can have 1 nickel and x dimes - they span at least the same range.

So you have exactly 1 nickel.

You need at least 2 dimes, since you want to get 20.

This means you have 4 pennies, 1 nickel and at least 2 dimes.

If you had less than 10 coins, you would have less than 3 quarters. But then the maximal possible change you could get using all coins is 4 + 5 + 20 + 50 = 79, not enough.

This means you have at least 10 coins. Thomas's answer shows that in fact if you have 4 pennies, 1 nickel, 2 dimes and 3 quarters, all is well.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

I have removed the scope and then used a maven update to solve this problem.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    **<!-- <scope>provided</scope> -->**
</dependency>

The jstl lib is not present in the tomcat lib folder.So we have to include it. I don't understand why we are told to keep both servlet-api and jstl's scope as provided.

How to restore/reset npm configuration to default values?

If you run npm config edit, you'll get an editor showing the current configuration, and also a list of options and their default values.

But I don't think there's a 'reset' command.

Using ls to list directories and their total sizes

These are all great suggestions, but the one I use is:

du -ksh * | sort -n -r

-ksh makes sure the files and folders are listed in a human-readable format and in megabytes, kilobytes, etc. Then you sort them numerically and reverse the sort so it puts the bigger ones first.

The only downside to this command is that the computer does not know that Gigabyte is bigger than Megabyte so it will only sort by numbers and you will often find listings like this:

120K
12M
4G

Just be careful to look at the unit.

This command also works on the Mac (whereas sort -h does not for example).

Return a value if no rows are found in Microsoft tSQL

SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]

FROM Sites S

WHERE S.Id = @SiteId and S.Status = 1 AND 
      (S.WebUserId = @WebUserId OR S.AllowUploads = 1)

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Try this one:

HTML:

<div id="para1"></div>

JavaScript:

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var d = new Date(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}

Result:

Mon Sep 18 2017 12:40pm

How do I check in JavaScript if a value exists at a certain array index?

Conceptually, arrays in JavaScript contain array.length elements, starting with array[0] up until array[array.length - 1]. An array element with index i is defined to be part of the array if i is between 0 and array.length - 1 inclusive. If i is not in this range it's not in the array.

So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

if (i >= 0 && i < array.length) {
  // it is in array
}

Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.

What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined. Maybe you even want to know if it's defined and not null. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length property, any new values will be undefined.

To determine if a given value is something meaningful, or has been defined. That is, not undefined, or null:

if (typeof array[index] !== 'undefined') {

or

if (typeof array[index] !== 'undefined' && array[index] !== null) {

Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:

if (array[index] != null) {
  // The == and != operators consider null equal to only null or undefined
}  

tap gesture recognizer - which object was tapped?

Typical 2019 example

Say you have a FaceView which is some sort of image. You're going to have many of them on screen (or, in a collection view, table, stack view or other list).

In the class FaceView you will need a variable "index"

class FaceView: UIView {
   var index: Int

so that each FaceView can be self-aware of "which" face it is on screen.

So you must add var index: Int to the class in question.

So you are adding many FaceView to your screen ...

let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.

You now add a click to f

f.addGestureRecognizer(UITapGestureRecognizer(target: self,
                           action: #selector(tapOneOfTheFaces)))

Here's the secret:

@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
    if let tapped = sender.view as? CirclePerson {
        print("we got it: \(tapped.index)")

You now know "which" face was clicked in your table, screen, stack view or whatever.

It's that easy.

How To: Execute command line in C#, get STD OUT results

You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.

java.lang.IllegalArgumentException: contains a path separator

String all = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String strLine;
            while ((strLine = br.readLine()) != null){
                all = all + strLine;
            }
        } catch (IOException e) {
            Log.e("notes_err", e.getLocalizedMessage());
        }

c# Best Method to create a log file

We did a lot of research into logging, and decided that NLog was the best one to use.

See http://nlog-project.org/

Also see log4net vs. Nlog and http://www.dotnetlogging.com/comparison/

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

Can you explain the HttpURLConnection connection process?

I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.

Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.

enter image description here

Below is my toy program and annotation

    /* Create a connection LOCAL object,
     * the openConnection() function DOES NOT initiate
     * any packet exchange with the remote server.
     * 
     * The configurations only setup the LOCAL
     * connection object properties.
     */
    HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    ...//headers setup
    byte[] testContent = {0x32, 0x32};

    /**
     * This triggers packet exchange with the remote
     * server to create a link. But writing/flushing
     * to a output stream does not send out any data.
     * 
     * Payload are buffered locally.
     */
    try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {
        outputStream.write(testContent);
        outputStream.flush();
    }

    /**
     * Trigger payload sending to the server.
     * Client get ALL responses (including response code,
     * message, and content payload) 
     */
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);

    /* Here no further exchange happens with remote server, since
     * the input stream content has already been buffered
     * in previous step
     */
    try (InputStream is = connection.getInputStream()) {
        Scanner scanner = new Scanner(is);
        StringBuilder stringBuilder = new StringBuilder();
        while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine()).append(System.lineSeparator());
        }
    }

    /**
     * Trigger the disconnection from the server.
     */
    String responsemsg = connection.getResponseMessage();
    System.out.println(responsemsg);
    connection.disconnect();

Telling Python to save a .txt file to a certain directory on Windows and Mac

Use os.path.join to combine the path to the Documents directory with the completeName (filename?) supplied by the user.

import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
    toFile = raw_input("Write what you want into the field")
    file1.write(toFile)

If you want the Documents directory to be relative to the user's home directory, you could use something like:

os.path.join(os.path.expanduser('~'),'Documents',completeName)

Others have proposed using os.path.abspath. Note that os.path.abspath does not resolve '~' to the user's home directory:

In [10]: cd /tmp
/tmp

In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

On the face of it, it does seem that requirements.txt and setup.py are silly duplicates, but it's important to understand that while the form is similar, the intended function is very different.

The goal of a package author, when specifying dependencies, is to say "wherever you install this package, these are the other packages you need, in order for this package to work."

In contrast, the deployment author (which may be the same person at a different time) has a different job, in that they say "here's the list of packages that we've gathered together and tested and that I now need to install".

The package author writes for a wide variety of scenarios, because they're putting their work out there to be used in ways they may not know about, and have no way of knowing what packages will be installed alongside their package. In order to be a good neighbor and avoid dependency version conflicts with other packages, they need to specify as wide a range of dependency versions as can possibly work. This is what install_requires in setup.py does.

The deployment author writes for a very different, very specific goal: a single instance of an installed application or service, installed on a particular computer. In order to precisely control a deployment, and be sure that the right packages are tested and deployed, the deployment author must specify the exact version and source-location of every package to be installed, including dependencies and dependency's dependencies. With this spec, a deployment can be repeatably applied to several machines, or tested on a test machine, and the deployment author can be confident that the same packages are deployed every time. This is what a requirements.txt does.

So you can see that, while they both look like a big list of packages and versions, these two things have very different jobs. And it's definitely easy to mix this up and get it wrong! But the right way to think about this is that requirements.txt is an "answer" to the "question" posed by the requirements in all the various setup.py package files. Rather than write it by hand, it's often generated by telling pip to look at all the setup.py files in a set of desired packages, find a set of packages that it thinks fits all the requirements, and then, after they're installed, "freeze" that list of packages into a text file (this is where the pip freeze name comes from).

So the takeaway:

  • setup.py should declare the loosest possible dependency versions that are still workable. Its job is to say what a particular package can work with.
  • requirements.txt is a deployment manifest that defines an entire installation job, and shouldn't be thought of as tied to any one package. Its job is to declare an exhaustive list of all the necessary packages to make a deployment work.
  • Because these two things have such different content and reasons for existing, it's not feasible to simply copy one into the other.

References:

Concat strings by & and + in VB.Net

You can write '&' to add string and integer :

processDetails=objProcess.ProcessId & ":" & objProcess.name
message = msgbox(processDetails,16,"Details")

output will be:

5577:wscript.exe

Changing ImageView source

Just write a method for changing imageview

public void setImage(final Context mContext, final ImageView imageView, int picture)
{
    if (mContext != null && imageView != null)
    {
        try
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture, mContext.getApplicationContext().getTheme()));
            } else
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture));
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get the second largest number in a list in linear time

Best solution that my friend Dhanush Kumar came up with:

    def second_max(loop):
        glo_max = loop[0]
        sec_max = float("-inf")
        for i in loop:
            if i > glo_max:
                sec_max = glo_max
                glo_max=i
            elif sec_max < i < glo_max:
                sec_max = i
        return sec_max
    
    #print(second_max([-1,-3,-4,-5,-7]))
    
    assert second_max([-1,-3,-4,-5,-7])==-3
    assert second_max([5,3,5,1,2]) == 3
    assert second_max([1,2,3,4,5,7]) ==5
    assert second_max([-3,1,2,5,-2,3,4]) == 4
    assert second_max([-3,-2,5,-1,0]) == 0
    assert second_max([0,0,0,1,0]) == 0

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Rather than disabling a new feature, I opted to follow the instructions of the error. In my global.asax.cs I added:

protected void Application_Start(object sender, EventArgs e)
{
    string JQueryVer = "1.7.1";
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
    {
        Path = "~/Scripts/jquery-" + JQueryVer + ".min.js",
        DebugPath = "~/Scripts/jquery-" + JQueryVer + ".js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".js",
        CdnSupportsSecureConnection = true,
        LoadSuccessExpression = "window.jQuery"
    });
}

This comes from an msdn blog post which highlights some of the advantages of script resource mappings. Of particular interest to me was centralized control over the delivery of the script files based on "debug=true", EnableCDN, etc.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

One way to debug this (and to make sure it is the protocol violation that is causing the problem), is to use Fiddler (Http Web Proxy) and see if the same error occurs. If it doesn't (i.e. Fiddler handled the issue for you) then you should be able to fix it using the UseUnsafeHeaderParsing flag.

If you are looking for a way to set this value programatically see the examples here: http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/

How to get child element by class name?

June 2018 update to ES6

    const doc = document.getElementById('test');
    let notes = null;
    for (const value of doc) {
        if (value.className === '4') {
            notes = value;
            break;
        }    
    }

ssh "permissions are too open" error

AFAIK the values are:

700 for the hidden directory ".ssh" where key file is located

600 for the keyfile "id_rsa"

What is Hash and Range Primary Key?

A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.

In a simple words range + hash key = composite primary key CoreComponents of Dynamodb enter image description here

A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.

So both have a different purpose and together help to do complex query. In the above example hashkey1 can have multiple n-range. Another example of range and hashkey is game, userA(hashkey) can play Ngame(range)

enter image description here

The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.

A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.

enter image description here

https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html

Should we pass a shared_ptr by reference or by value?

Here's Herb Sutter's take

Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.

Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.

Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).

How to playback MKV video in web browser?

HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:

DivX Web Player (NPAPI browsers only)

AC3 Audio Decoder

And here is the HTML:

<embed id="divxplayer" type="video/divx" width="1024" height="768" 
src ="path_to_file" autoPlay=\"true\" 
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>

The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

Generate PDF from Swagger API documentation

You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.

If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).

  1. rest-api -> swagger.json : swagger-maven-plugin
  2. swagger.json -> Asciidoc : swagger2markup-maven-plugin
  3. Asciidoc -> PDF : asciidoctor-maven-plugin

Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.3</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>false</springmvc>
                <locations>some.package</locations>
                <basePath>/api</basePath>
                <info>
                    <title>Put your REST service's name here</title>
                    <description>Add some description</description>
                    <version>v1</version>
                </info>
                <swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
                <attachSwaggerArtifact>true</attachSwaggerArtifact>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <!-- fx process-classes phase -->
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>io.github.robwin</groupId>
    <artifactId>swagger2markup-maven-plugin</artifactId>
    <version>0.9.3</version>
    <configuration>
        <inputDirectory>${project.build.directory}/api</inputDirectory>
        <outputDirectory>${generated.asciidoc.directory}</outputDirectory>
        <!-- specify location to place asciidoc files -->
        <markupLanguage>asciidoc</markupLanguage>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-swagger</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.3</version>
    <dependencies>
        <dependency>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoctorj-pdf</artifactId>
            <version>1.5.0-alpha.11</version>
        </dependency>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
    <configuration>
        <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
        <!-- You will need to create an .adoc file. This is the input to this plugin -->
        <sourceDocumentName>swagger.adoc</sourceDocumentName>
        <attributes>
            <doctype>book</doctype>
            <toc>left</toc>
            <toclevels>2</toclevels>
            <generated>${generated.asciidoc.directory}</generated>
            <!-- this path is referenced in swagger.adoc file. The given file will simply 
                point to the previously create adoc files/assemble them. -->
        </attributes>
    </configuration>
    <executions>
        <execution>
            <id>asciidoc-to-html</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>html5</backend>
                <outputDirectory>${generated.html.directory}</outputDirectory>
                <!-- specify location to place html file -->
            </configuration>
        </execution>
        <execution>
            <id>asciidoc-to-pdf</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>pdf</backend>
                <outputDirectory>${generated.pdf.directory}</outputDirectory>
                <!-- specify location to place pdf file -->
            </configuration>
        </execution>
    </executions>
</plugin>

The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:

include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]

If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <warSourceDirectory>WebContent</warSourceDirectory>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <webResources>
            <resource>
                <directory>${generated.html.directory}</directory>
            <!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
            </resource>
            <resource>
                <directory>${generated.pdf.directory}</directory>
            <!-- Add swagger.html to WAR file, so as to make it available as static content. -->
            </resource>
        </webResources>
    </configuration>
</plugin>

The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.

Can I position an element fixed relative to parent?

Here is an example of Jon Adams suggestion above in order to fix a div (toolbar) to the right hand side of your page element using jQuery. The idea is to find the distance from the right hand side of the viewport to the right hand side of the page element and to keep the right hand side of the toolbar there!

HTML

<div id="pageElement"></div>
<div id="toolbar"></div>

CSS

#toolbar {
    position: fixed;
}
....

jQuery

function placeOnRightHandEdgeOfElement(toolbar, pageElement) {
    $(toolbar).css("right", $(window).scrollLeft() + $(window).width()
    - $(pageElement).offset().left
    - parseInt($(pageElement).css("borderLeftWidth"),10)
    - $(pageElement).width() + "px");
}
$(document).ready(function() {
    $(window).resize(function() {
        placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
    });
    $(window).scroll(function () { 
        placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
    });
    $("#toolbar").resize();
});

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

Is a LINQ statement faster than a 'foreach' loop?

You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

Break when a value changes using the Visual Studio debugger

You can also choose to break explicitly in code:

// Assuming C#
if (condition)
{
    System.Diagnostics.Debugger.Break();
}

From MSDN:

Debugger.Break: If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit.

This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:

chkdsk /F e:

This can be run from the search windows box or from a cmd prompt. The /F fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.

MySQL CONCAT returns NULL if any field contain NULL

Use CONCAT_WS instead:

CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

How to check if a user is logged in (how to properly use user.is_authenticated)?

In your view:

{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}

In you controller functions add decorator:

from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

How to compile makefile using MinGW?

Excerpt from http://www.mingw.org/wiki/FAQ:

What's the difference between make and mingw32-make?

The "native" (i.e.: MSVCRT dependent) port of make is lacking in some functionality and has modified functionality due to the lack of POSIX on Win32. There also exists a version of make in the MSYS distribution that is dependent on the MSYS runtime. This port operates more as make was intended to operate and gives less headaches during execution. Based on this, the MinGW developers/maintainers/packagers decided it would be best to rename the native version so that both the "native" version and the MSYS version could be present at the same time without file name collision.

So,look into C:\MinGW\bin directory and first make sure what make executable, have you installed.(make.exe or mingw32-make.exe)

Before using MinGW, you should add C:\MinGW\bin; to the PATH environment variable using the instructions mentioned at http://www.mingw.org/wiki/Getting_Started/

Then cd to your directory, where you have the makefile and Try using mingw32-make.exe makefile.in or simply make.exe makefile.in(depending on executables in C:\MinGW\bin).

If you want a GUI based solution, install DevCPP IDE and then re-make.

Update query PHP MySQL

Update a row or column of a table

$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";

if ($con->query($update) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

Entity Framework The underlying provider failed on Open

  1. Search "Component Services" in Programs and Files
  2. Go to Services
  3. Find "Distributed Transaction Coordinator" Service
  4. Right click and Restart the Service

You've just done a restart of the service and the code should run without errors

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

Angular-cli from css to scss

Open angular.json file

1.change from

"schematics": {}

to

"schematics": {
           "@schematics/angular:component": {
                   "styleext": "scss"       
             }  
  }
  1. change from (at two places)

"src/styles.css"

to

"src/styles.scss"

then check and rename all .css files and update component.ts files styleUrls from .css to .scss

Unit Testing C Code

I used RCUNIT to do some unit testing for embedded code on PC before testing on the target. Good hardware interface abstraction is important else endianness and memory mapped registers are going to kill you.

Can I multiply strings in Java to repeat sequences?

A generalisation of Dave Hartnoll's answer (I am mainly taking the concept ad absurdum, maybe don't use that in anything where you need speed). This allows one to fill the String up with i characters following a given pattern.

int i = 3;
String someNum = "123";
String pattern = "789";
someNum += "00000000000000000000".replaceAll("0",pattern).substring(0, i);

If you don't need a pattern but just any single character you can use that (it's a tad faster):

int i = 3;
String someNum = "123";
char c = "7";
someNum += "00000000000000000000".replaceAll("0",c).substring(0, i);

ExecuteReader: Connection property has not been initialized

All of the answers is true.This is another way. And I like this One

SqlCommand cmd = conn.CreateCommand()

you must notice that strings concat have a sql injection problem. Use the Parameters http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx