Programs & Examples On #Opcodes

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

Top guy is probably right that you downloaded instead of cloning the repo at start. Here is a easy solution without getting too technical.

  • In a new editor window, clone your repo in another directory.
  • Make a new branch.
  • Then copy from your your edited editor window into your new repo by copy paste.

Make sure that all your edits are copied over by looking at your older github branch.

TypeScript: Property does not exist on type '{}'

I suggest the following change

let propertyName =  {} as any;

PHP "php://input" vs $_POST

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3

But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).

The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

Get index of clicked element in collection with jQuery

Just do this way:-

$('ul li').on('click', function(e) {
    alert($(this).index()); 
});

OR

$('ul li').click(function() {
    alert($(this).index());
});

Get event listeners attached to node using addEventListener

Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):

var ListenerTracker=new function(){
    var is_active=false;
    // listener tracking datas
    var _elements_  =[];
    var _listeners_ =[];
    this.init=function(){
        if(!is_active){//avoid duplicate call
            intercep_events_listeners();
        }
        is_active=true;
    };
    // register individual element an returns its corresponding listeners
    var register_element=function(element){
        if(_elements_.indexOf(element)==-1){
            // NB : split by useCapture to make listener easier to find when removing
            var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
            _elements_.push(element);
            _listeners_.push(elt_listeners);
        }
        return _listeners_[_elements_.indexOf(element)];
    };
    var intercep_events_listeners = function(){
        // backup overrided methods
        var _super_={
            "addEventListener"      : HTMLElement.prototype.addEventListener,
            "removeEventListener"   : HTMLElement.prototype.removeEventListener
        };

        Element.prototype["addEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["addEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;

            if(!listeners[useCapture][type])listeners[useCapture][type]=[];
            listeners[useCapture][type].push(listener);
        };
        Element.prototype["removeEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["removeEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;
            if(!listeners[useCapture][type])return;
            var lid = listeners[useCapture][type].indexOf(listener);
            if(lid>-1)listeners[useCapture][type].splice(lid,1);
        };
        Element.prototype["getEventListeners"]=function(type){
            var listeners=register_element(this);
            // convert to listener datas list
            var result=[];
            for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
                if(typeof(type)=="string"){// filtered by type
                    if(list[type]){
                        for(var id in list[type]){
                            result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
                        }
                    }
                }else{// all
                    for(var _type in list){
                        for(var id in list[_type]){
                            result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
                        }
                    }
                }
            }
            return result;
        };
    };
}();
ListenerTracker.init();

Generate GUID in MySQL for existing Data?

Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.

For reference:

UPDATE some_table SET some_field=(SELECT uuid());

This worked perfectly on its own. But when I tried this:

UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));

Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.

UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));

It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.

To resolve this, I just split it into two queries:

UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');

Simple solution, obviously, but hopefully this will save someone the time that I just lost.

Mailto: Body formatting

Use %0D%0A for a line break in your body

Example (Demo):

<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
                                                                  ^^^^^^

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR

Don't rescue Exception => e (and not re-raise the exception) - or you might drive off a bridge.


Let's say you are in a car (running Ruby). You recently installed a new steering wheel with the over-the-air upgrade system (which uses eval), but you didn't know one of the programmers messed up on syntax.

You are on a bridge, and realize you are going a bit towards the railing, so you turn left.

def turn_left
  self.turn left:
end

oops! That's probably Not Good™, luckily, Ruby raises a SyntaxError.

The car should stop immediately - right?

Nope.

begin
  #...
  eval self.steering_wheel
  #...
rescue Exception => e
  self.beep
  self.log "Caught #{e}.", :warn
  self.log "Logged Error - Continuing Process.", :info
end

beep beep

Warning: Caught SyntaxError Exception.

Info: Logged Error - Continuing Process.

You notice something is wrong, and you slam on the emergency breaks (^C: Interrupt)

beep beep

Warning: Caught Interrupt Exception.

Info: Logged Error - Continuing Process.

Yeah - that didn't help much. You're pretty close to the rail, so you put the car in park (killing: SignalException).

beep beep

Warning: Caught SignalException Exception.

Info: Logged Error - Continuing Process.

At the last second, you pull out the keys (kill -9), and the car stops, you slam forward into the steering wheel (the airbag can't inflate because you didn't gracefully stop the program - you terminated it), and the computer in the back of your car slams into the seat in front of it. A half-full can of Coke spills over the papers. The groceries in the back are crushed, and most are covered in egg yolk and milk. The car needs serious repair and cleaning. (Data Loss)

Hopefully you have insurance (Backups). Oh yeah - because the airbag didn't inflate, you're probably hurt (getting fired, etc).


But wait! There's more reasons why you might want to use rescue Exception => e!

Let's say you're that car, and you want to make sure the airbag inflates if the car is exceeding its safe stopping momentum.

 begin 
    # do driving stuff
 rescue Exception => e
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
    raise
 end

Here's the exception to the rule: You can catch Exception only if you re-raise the exception. So, a better rule is to never swallow Exception, and always re-raise the error.

But adding rescue is both easy to forget in a language like Ruby, and putting a rescue statement right before re-raising an issue feels a little non-DRY. And you do not want to forget the raise statement. And if you do, good luck trying to find that error.

Thankfully, Ruby is awesome, you can just use the ensure keyword, which makes sure the code runs. The ensure keyword will run the code no matter what - if an exception is thrown, if one isn't, the only exception being if the world ends (or other unlikely events).

 begin 
    # do driving stuff
 ensure
    self.airbags.inflate if self.exceeding_safe_stopping_momentum?
 end

Boom! And that code should run anyways. The only reason you should use rescue Exception => e is if you need access to the exception, or if you only want code to run on an exception. And remember to re-raise the error. Every time.

Note: As @Niall pointed out, ensure always runs. This is good because sometimes your program can lie to you and not throw exceptions, even when issues occur. With critical tasks, like inflating airbags, you need to make sure it happens no matter what. Because of this, checking every time the car stops, whether an exception is thrown or not, is a good idea. Even though inflating airbags is a bit of an uncommon task in most programming contexts, this is actually pretty common with most cleanup tasks.

Predicate in Java

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true to a function instead of defining a named Tautology subclass like the above.

What's the difference between git clone --mirror and git clone --bare

A clone copies the refs from the remote and stuffs them into a subdirectory named 'these are the refs that the remote has'.

A mirror copies the refs from the remote and puts them into its own top level - it replaces its own refs with those of the remote.

This means that when someone pulls from your mirror and stuffs the mirror's refs into thier subdirectory, they will get the same refs as were on the original. The result of fetching from an up-to-date mirror is the same as fetching directly from the initial repo.

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

SQL to Query text in access with an apostrophe in it

You escape ' by doubling it, so:

Select * from tblStudents where name like 'Daniel O''Neal' 

Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.

Stopping Docker containers by image name - Ubuntu

Following issue 8959, a good start would be:

docker ps -a -q --filter="name=<containerName>"

Since name refers to the container and not the image name, you would need to use the more recent Docker 1.9 filter ancestor, mentioned in koekiebox's answer.

docker ps -a -q  --filter ancestor=<image-name>

As commented below by kiril, to remove those containers:

stop returns the containers as well.

So chaining stop and rm will do the job:

docker rm $(docker stop $(docker ps -a -q --filter ancestor=<image-name> --format="{{.ID}}"))

MYSQL import data from csv using LOAD DATA INFILE

You can try to insert like this :

LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Getting a list of files in a directory with a glob

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end

How Can I Remove “public/index.php” in the URL Generated Laravel?

If you use IIS Windows Server add web.config file in root folder and put the below code :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{URL}" pattern="^system.*" ignoreCase="false" />
                    </conditions>
                    <action type="Rewrite" url="/index.php/{R:1}" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{R:1}" pattern="^(index\.php|images|robots\.txt|css)" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

and if you use .htaccess use this one :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

"Could not find a valid gem in any repository" (rubygame and others)

Make sure you type the command from the "App" Directory

How to fetch Java version using single line command in Linux

  1. Redirect stderr to stdout.
  2. Get first line
  3. Filter the version number.

    java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
    

Why emulator is very slow in Android Studio?

In my case, the problem was coming from the execution of WinSAT.exe (located in System32 folder). I disabled it and issue solved.

To turn it off:

  1. Start > Task Scheduler (taskschd.msc)
  2. Find Task Scheduler (Local)
  3. Task Scheduler Library
  4. Microsoft > Windows > Maintenance
  5. Right click WinSAT
  6. Select disable.

The Reference

Also, suppress it from Task Manager or simply reboot your machine.


Point: In this situation (when the problem comes from WinSAT) emulator works (with poor performance) when you use Software - GLES 2.0 and works with very very poor performance when you use Hardware - GLES 2.0.

Case insensitive regular expression without re.compile?

You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):

re.search(r'(?i)test', 'TeSt').group()    ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group()     ## returns 'TeSt'

Determine what user created objects in SQL Server

If you need a small and specific mechanism, you can search for DLL Triggers info.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Spring boot - Not a managed type

Configure the location of entities using @EntityScan in Spring Boot entry point class.

Update on Sept 2016: For Spring Boot 1.4+:
use org.springframework.boot.autoconfigure.domain.EntityScan
instead of org.springframework.boot.orm.jpa.EntityScan, as ...boot.orm.jpa.EntityScan is deprecated as of Spring Boot 1.4

When to use %r instead of %s in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

Create a list with initial capacity in Python

I ran S.Lott's code and produced the same 10% performance increase by preallocating. I tried Ned Batchelder's idea using a generator and was able to see the performance of the generator better than that of the doAllocate. For my project the 10% improvement matters, so thanks to everyone as this helps a bunch.

def doAppend(size=10000):
    result = []
    for i in range(size):
        message = "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate(size=10000):
    result = size*[None]
    for i in range(size):
        message = "some unique object %d" % ( i, )
        result[i] = message
    return result

def doGen(size=10000):
    return list("some unique object %d" % ( i, ) for i in xrange(size))

size = 1000
@print_timing
def testAppend():
    for i in xrange(size):
        doAppend()

@print_timing
def testAlloc():
    for i in xrange(size):
        doAllocate()

@print_timing
def testGen():
    for i in xrange(size):
        doGen()


testAppend()
testAlloc()
testGen()

Output

testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms

Parse an HTML string with JS

1 Way

Use document.cloneNode()

Performance is:

Call to document.cloneNode() took ~0.22499999977299012 milliseconds.

and maybe will be more.

_x000D_
_x000D_
var t0, t1, html;

t0 = performance.now();
   html = document.cloneNode(true);
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));
_x000D_
_x000D_
_x000D_

2 Way

Use document.implementation.createHTMLDocument()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.14000000010128133 milliseconds.

_x000D_
_x000D_
var t0, t1, html;

t0 = performance.now();
html = document.implementation.createHTMLDocument("test");
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));
_x000D_
_x000D_
_x000D_

3 Way

Use document.implementation.createDocument()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.14000000010128133 milliseconds.

var t0 = performance.now();
  html = document.implementation.createDocument('', 'html', 
             document.implementation.createDocumentType('html', '', '')
         );
var t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test</div></body></html>';

console.log(html.getElementById("test1"));

4 Way

Use new Document()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.13499999840860255 milliseconds.

  • Note

ParentNode.append is experimental technology in 2020 year.

var t0, t1, html;

t0 = performance.now();
//---------------
html = new Document();

html.append(
  html.implementation.createDocumentType('html', '', '')
);
    
html.append(
  html.createElement('html')
);
//---------------
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));

Using NULL in C++?

From crtdbg.h (and many other headers):

#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else
#define NULL    ((void *)0)
#endif
#endif

Therefore NULL is 0, at least on the Windows platform. So no, not that I know of.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

To restore your Homebrew setup try this:

cd /usr/local/Homebrew/Library && git stash && git clean -d -f && git reset --hard && git pull

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

Could not find a part of the path ... bin\roslyn\csc.exe

Per a comment by Daniel Neel above :

version 1.0.3 of the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package works for me, but version 1.0.6 causes the error in this question

Downgrading to 1.0.3 resolved this issue for me.

What's the difference between `raw_input()` and `input()` in Python 3?

In Python 3, raw_input() doesn't exist which was already mentioned by Sven.

In Python 2, the input() function evaluates your input.

Example:

name = input("what is your name ?")
what is your name ?harsha

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    name = input("what is your name ?")
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":

>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha

raw_input()

The raw_input()` function doesn't evaluate, it will just read whatever you enter.

Example:

name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'

Example:

 name = eval(raw_input("what is your name?"))
what is your name?harsha

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    name = eval(raw_input("what is your name?"))
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In example above, I was just trying to evaluate the user input with the eval function.

Remove by _id in MongoDB console

Well, the _id is an object in your example, so you just need to pass an object

'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'

This should work

Edit: Added trailing paren to ensure that it compiled.

How can I INSERT data into two tables simultaneously in SQL Server?

I was also struggling with this problem, and find that the best way is to use a CURSOR.

I have tried Denis solution with OUTPUT, but as he mentiond, it's impossible to output external columns in an insert statement, and the MERGE can't work when insert multiple rows by select.

So, i've used a CURSOR, for each row in the outer table, i've done a INSERT, then use the @@IDENTITY for another INSERT.

DECLARE @OuterID int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT  ID FROM   [external_Table]

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @OuterID

WHILE @@FETCH_STATUS = 0
BEGIN 
INSERT INTO [Table]   (data)
    SELECT data
    FROM     [external_Table] where ID = @OuterID 

    INSERT INTO [second_table] (FK,OuterID)
    VALUES(@OuterID,@@identity)

    FETCH NEXT FROM MY_CURSOR INTO @OuterID
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

How to get current working directory in Java?

Use CodeSource#getLocation(). This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

For a minimum API level of 15, you'd want to use AppCompatActivity. So for example, your MainActivity would look like this:

public class MainActivity extends AppCompatActivity {
    ....
    ....
}

To use the AppCompatActivity, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:

compile 'com.android.support:appcompat-v7:22:2.0'

You can use this AppCompat as your main Activity, which can then be used to launch Fragments or other Activities (this depends on what kind of app you're building).

The BigNerdRanch book is a good resource, but yeah, it's outdated. Read it for general information on how Android works, but don't expect the specific classes they use to be up to date.

apc vs eaccelerator vs xcache

In all tests I have seen, eAccelerator performs faster than any other cache out there and uses less memeory to do so. It comes with a nifty script to view cache utilisation and clear the cache etc. eAccelerator is compatible with xdebug and Zend Optimizer.

APC is being included in PHP because it is being maintained by the PHP developers. It performs very well, but not as good as eAccelerator. And it has compatability issues with Zend Optimizer.

Xcache was made by the developers of lighttpd, benchmarks show it performs similiarly to eAccelerator, and faster than APC.

So which is the best?

APC = Great if you want an easy cache that will always work with PHP, no fuss. eAccelerator = If you have time to maintain it, keep it up todate and understand how it works, it will perform faster. Long term support not as certain as APC because APC is done by the PHP devs.

Oracle 12c Installation failed to access the temporary location

Summarized: Oracle under Windows has problems with usernames containing non-English letters or special characters:

If your machine is fresh installed, first look here. All the network related or 32 vs. 64 related issues may be not significant for you:

As others already pointed out partly, this error is highly related to the name of the TEMP dir. It occurred to me when installing Oracle 11g first time on a totally fresh Windows (e.g. Server 2008 R2 or Win 7, not important).

As I found out, on my machine the problem was, that the username contained a German special character ("ö"). Moreover Oracle cannot handle any special character, I assume, the TEMP path is limited to letters. Other colleagues here have reported problems with underscore and chinese characters.

Explanation: In Windows the TEMP dir (environment variable %TEMP%) is by default in the user directory, for example:

C:\Users\ThisUser\AppData\Local\Temp

If "ThisUser" contains special or non-ASCII characters, then in this case this affects the TEMP path, and that is where Oracle is gettings problems.

Setting the TEMP dir to different directory is of course another possibility instead of installing with another username.

Moreover, Oracle is not a fully native Windows citizen which everybody will recognize, if he opens the Oracle install logfile with notepad ;-) Obviously, this is not programmed cleanly and portable, e.g. with using "std::endl" instead of "\n" . (Yes, Notepad++ and other editors do the job.)

Overall, my impression is, if the database were of the same quality as it's installer, Oracle would not be so successful ..

Last remark: Yes, after failed install because of the special characters you see only one Oracle service named OracleRemExecService, but there is no reason to stop this manually as recommended in other solutions, if you are able to install again a fresh OS..

Get difference between 2 dates in JavaScript?

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

HTML form input tag name element array with JavaScript

Here’s some PHP and JavaScript demonstration code that shows a simple way to create indexed fields on a form (fields that have the same name) and then process them in both JavaScript and PHP. The fields must have both "ID" names and "NAME" names. Javascript uses the ID and PHP uses the NAME.

<?php
// How to use same field name multiple times on form
// Process these fields in Javascript and PHP
// Must use "ID" in Javascript and "NAME" in PHP 
echo "<HTML>";
echo "<HEAD>";
?>
<script type="text/javascript">
function TestForm(form) {
// Loop through the HTML form field (TheId) that is returned as an array. 
// The form field has multiple (n) occurrences on the form, each which has the same name.
// This results in the return of an array of elements indexed from 0 to n-1.
// Use ID  in Javascript
var i = 0;
document.write("<P>Javascript responding to your button click:</P>");
for (i=0; i < form.TheId.length; i++) {
  document.write(form.TheId[i].value);
  document.write("<br>");
}  
}
</script>
<?php
echo "</HEAD>";
echo "<BODY>";
$DQ = '"';  # Constant for building string with double quotes in it.

if (isset($_POST["MyButton"])) {
  $TheNameArray = $_POST["TheName"];  # Use NAME in PHP
  echo "<P>Here are the names you submitted to server:</P>";
  for ($i = 0; $i <3; $i++) {   
    echo $TheNameArray[$i] . "<BR>";
  } 
}
echo "<P>Enter names and submit to server or Javascript</P>";
echo "<FORM NAME=TstForm METHOD=POST ACTION=" ;
echo $DQ . "TestArrayFormToJavascript2.php" . $DQ . "OnReset=" . $DQ . "return allowreset(this)" . $DQ . ">";
echo "<FORM>";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<P><INPUT TYPE=submit NAME=MyButton VALUE=" . $DQ . "Submit to server"    . $DQ . "></P>";
echo "<P><BUTTON onclick=" . $DQ . "TestForm(this.form)" . $DQ . ">Submit to Javascript</BUTTON></P>"; 
echo "</FORM>";
echo "</BODY>";
echo "</HTML>";

mysql extract year from date format

try this code:

SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate

Including .cpp files

What include does is copying all the contents from the file (which is the argument inside the <> or the "" ), so when the preproccesor finishes its work main.cpp will look like:

// iostream stuff

int foo(int a){
    return ++a;
}

int main(int argc, char *argv[])
{
   int x=42;
   std::cout << x <<std::endl;
   std::cout << foo(x) << std::endl;
   return 0;
}

So foo will be defined in main.cpp, but a definition also exists in foop.cpp, so the compiler "gets confused" because of the function duplication.

Bootstrap 3 jquery event for active tab change

This worked for me.

$('.nav-pills > li > a').click( function() {
    $('.nav-pills > li.active').removeClass('active');
    $(this).parent().addClass('active');
} );

Bootstrap 3 unable to display glyphicon properly

This is the official documentation supporting the above answers.

Changing the icon font location Bootstrap assumes icon font files will be located in the ../fonts/ directory, relative to the compiled CSS files. Moving or renaming those font files means updating the CSS in one of three ways: Change the @icon-font-path and/or @icon-font-name variables in the source Less files. Utilize the relative URLs option provided by the Less compiler. Change the url() paths in the compiled CSS. Use whatever option best suits your specific development setup.

Other than this one mistake the new users would do is, after downloading the bootstrap zip from the official website. They would tend to skip the fonts folder for copying in their dev setup. So missing fonts folder can also lead to this problem

How to verify element present or visible in selenium 2 (Selenium WebDriver)

webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();

Node.js: How to read a stream into a buffer?

in ts, [].push(bufferPart) is not compatible;

so:

getBufferFromStream(stream: Part | null): Promise<Buffer> {
    if (!stream) {
        throw 'FILE_STREAM_EMPTY';
    }
    return new Promise(
        (r, j) => {
            let buffer = Buffer.from([]);
            stream.on('data', buf => {
               buffer = Buffer.concat([buffer, buf]);
            });
            stream.on('end', () => r(buffer));
            stream.on('error', j);
        }
    );
}

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

You have a mismatch of two different collations in your table. You can check what collations each column in your table(s) has by using this query:

SELECT
    col.name, col.collation_name
FROM 
    sys.columns col
WHERE
    object_id = OBJECT_ID('YourTableName')

Collations are needed and used when ordering and comparing strings. It's generally a good idea to have a single, unique collation used throughout your database - don't use different collations within a single table or database - you're only asking for trouble....

Once you've settled for one single collation, you can change those tables / columns that don't match yet using this command:

ALTER TABLE YourTableName
  ALTER COLUMN OffendingColumn
    VARCHAR(100) COLLATE Latin1_General_CI_AS NOT NULL

Marc

UPDATE: to find the fulltext indices in your database, use this query here:

SELECT
    fti.object_Id,
    OBJECT_NAME(fti.object_id) 'Fulltext index',
    fti.is_enabled,
    i.name 'Index name',
    OBJECT_NAME(i.object_id) 'Table name'
FROM 
    sys.fulltext_indexes fti
INNER JOIN 
    sys.indexes i ON fti.unique_index_id = i.index_id

You can then drop the fulltext index using:

DROP FULLTEXT INDEX ON (tablename)

Attaching click to anchor tag in angular

I think you are not letting Angular work for you.

In angular 2:

  1. Remove the href tag from <a> to prevent a page forwarding.
  2. Then just add your usual Angular click attribute and function.
  3. Add to style: "cursor: pointer" to make it act like a button

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

Docker: Container keeps on restarting again on again

try running

docker stop CONTAINER_ID & docker rm -v CONTAINER_ID

Thanks

How do I simulate a hover with a touch in touch enabled browsers?

Use can use CSS too, add focus and active (for IE7 and under) to the hidden link. Example of a ul menu inside a div with class menu:

.menu ul ul {display:none; position:absolute; left:100%; top:0; padding:0;}
.menu ul ul ul {display:none; position:absolute; top:0; left:100%;}
.menu ul ul a, .menu ul ul a:focus, .menu ul ul a:active { width:170px; padding:4px 4%; background:#e77776; color:#fff; margin-left:-15px; }
.menu ul li:hover > ul { display:block; }
.menu ul li ul li {margin:0;}

It's late and untested, should work ;-)

"Sources directory is already netbeans project" error when opening a project from existing sources

The advice here about removing the nbproject directory is not quite the whole story.

What Netbeans seems to do (and we are guessing at reverse engineering here) is to look for an xml file which has opening and closing project tags in it. This it concludes is evidence of an already existing project. Now if your files have an nbproject directory there, that will contain a project.xml file which contains the said tags. So removing that will do what you want.

But, my files don't have a nbproject directory but still NetBeans tells me there is an existing project maybe in memory. The reason is: my files include a file called pom.xml and that contains the said project tags in the xml (it was created by an entirely different system). Once that xml file is removed, then NetBeans will create an html project for me importing my code.

In sum: look through any xml files in you existing code, and be wary of project tags.

Dropdown using javascript onchange

easy

<script>
jQuery.noConflict()(document).ready(function() {
    $('#hide').css('display','none');
    $('#plano').change(function(){

        if(document.getElementById('plano').value == 1){
            $('#hide').show('slow');    

        }else 
            if(document.getElementById('plano').value == 0){

             $('#hide').hide('slow'); 
        }else
            if(document.getElementById('plano').value == 0){
             $('#hide').css('display','none');  

            }

    });
    $('#plano').change();
});
</script>

this example shows and hides the div if selected in combobox some specific value

How to remove error about glyphicons-halflings-regular.woff2 not found

I tried all the suggestions above, but my actual issue was that my application was looking for the /font folder and its contents (.woff etc) in app/fonts, but my /fonts folder was on the same level as /app. I moved /fonts under /app, and it works fine now. I hope this helps someone else roaming the web for an answer.

jQuery UI Tabs - How to Get Currently Selected Tab Index

If you need to get the tab index from outside the context of a tabs event, use this:

function getSelectedTabIndex() { 
    return $("#TabList").tabs('option', 'selected');
}

Update: From version 1.9 'selected' is changed to 'active'

$("#TabList").tabs('option', 'active')

Adding Image to xCode by dragging it from File

For xCode 10, first you need to add the image in your assetsCatalogue and then type this:

let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))

For beginners, let imageView is the name of the UIImageView object we are about to create.

An example for embedding an image into a viewControler file would look like this:

import UIKit

class TutorialViewCotroller: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
        view.addSubview(imageView)
    }
}

Please notice that I did not use any extension for the image file name, as in my case it is a group of images.

MySQL check if a table exists without throwing an exception

This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.

For mysql* I used :

if (mysqli_num_rows(
    mysqli_query(
                    $con,"SHOW TABLES LIKE '" . $table . "'")
                ) > 0
        or die ("No table set")
    ){

In PDO I used:

if ($con->query(
                   "SHOW TABLES LIKE '" . $table . "'"
               )->rowCount() > 0
        or die("No table set")
   ){

With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Correct way to find max in an Array in Swift

You can also sort your array and then use array.first or array.last

How to pull specific directory with git

Maybe this command can be helpful :

git archive --remote=MyRemoteGitRepo --format=tar BranchName_or_commit  path/to/your/dir/or/file > files.tar

"Et voilà"

reading text file with utf-8 encoding using java

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

How to create a POJO?

POJO class acts as a bean which is used to set and get the value.

public class Data
{


private int id;
    private String deptname;
    private String date;
    private String name;
    private String mdate;
    private String mname;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMdate() {
        return mdate;
    }

    public void setMdate(String mdate) {
        this.mdate = mdate;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }
}

How to declare array of zeros in python (or an array of a certain size)

The question says "How to declare array of zeros ..." but then the sample code references the Python list:

buckets = []   # this is a list

However, if someone is actually wanting to initialize an array, I suggest:

from array import array

my_arr = array('I', [0] * count)

The Python purist might claim this is not pythonic and suggest:

my_arr = array('I', (0 for i in range(count)))

The pythonic version is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.

How to return values in javascript

You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.

Then you can pass in the array, object literal, or custom object into a method to disseminate the values.

Object example:

function myFunction(value1,value2,value3)
{
     var returnedObject = {};
     returnedObject["value1"] = value1;
     returnedObject["value2"] = value2;
     return returnedObject;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue.value1  && returnValue.value2)
{
//Do some stuff
}

Array example:

function myFunction(value1,value2,value3)
{
     var returnedArray = [];
     returnedArray.push(value1);
     returnedArray.push(value2);
     return returnedArray;
}

var returnValue = myFunction("1",value2,value3);

if(returnValue[0]  && returnValue[1])
{
//Do some stuff
}

Custom Object:

function myFunction(value1,value2,value3)
{
     var valueHolder = new ValueHolder(value1, value2);
     return valueHolder;
}

var returnValue = myFunction("1",value2,value3);

// hypothetical method that you could build to create an easier to read conditional 
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}

I would avoid the array method because you would have to access the values via indices rather than named object properties.

angular ng-repeat in reverse

I would sugest using array native reverse method is always better choice over creating filter or using $index.

<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>

Plnkr_demo.

PHP Echo a large block of text

Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).

The error in your code is caused by the unescaped single quotes which appear in the string.

See this line:

$('input_6').hint('ex: [email protected]');

You'd need to escape those single quotes in a PHP string whether it's a single line or not.

There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:

if (is_single()) {
  ?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css"> 
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}

.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style> 

<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" /> 
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script> 
<script src="http://jotform.com/js/location.js" type="text/javascript"></script> 
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script> 
<script type="text/javascript"> 

JotForm.init(function(){
$('input_6').hint('ex: [email protected]');
});
</script>
  <?php
}else {

}

Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.

What is the purpose of Looper and how to use it?

You can better understand what Looper is in the context of GUI framework. Looper is made to do 2 things.

1) Looper transforms a normal thread, which terminates when its run() method return, into something run continuously until Android app is running, which is needed in GUI framework (Technically, it still terminates when run() method return. But let me clarify what I mean in below).

2) Looper provides a queue where jobs to be done are enqueued, which is also needed in GUI framework.

As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not some secret, special thread. It's just a normal thread similar to threads you create with new Thread() code, which means it terminates when its run() method return! Think of below example.

public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

Now, let's apply this simple principle to Android apps. What would happen if an Android app runs on normal thread? A thread called "main" or "UI" or whatever starts your application, and draws all UI. So, the first screen is displayed to users. So what now? The main thread terminates? No, it shouldn’t. It should wait until users do something, right? But how can we achieve this behavior? Well, we can try with Object.wait() or Thread.sleep(). For example, main thread finishes its initial job to display first screen, and sleeps. It awakes, which means interrupted, when a new job to do is fetched. So far so good, but at this moment we need a queue-like data structure to hold multiple jobs. Think about a case when a user touches screen serially, and a task takes longer time to finish. So, we need to have a data structure to hold jobs to be done in first-in-first-out manner. Also, you may imagine, implementing ever-running-and-process-job-when-arrived thread using interrupt is not easy, and leads to complex and often unmaintainable code. We'd rather create a new mechanism for such purpose, and that is what Looper is all about. The official document of Looper class says, "Threads by default do not have a message loop associated with them", and Looper is a class "used to run a message loop for a thread". Now you can understand what it means.

To make things more clear, let's check the code where main thread is transformed. It all happens in ActivityThread class. In its main() method, you can find below code, which turns a normal main thread into something what we need.

public final class ActivityThread {
    ...
    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        Looper.loop();
        ...
    }
}

and Looper.loop() method loop infinitely and dequeue a message and process one at a time:

public static void loop() {
    ...
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        msg.target.dispatchMessage(msg);
        ...
    }
}

So, basically Looper is a class that is made to address a problem that occurs in GUI framework. But this kind of needs can also happen in other situation as well. Actually it is a pretty famous pattern for multi threads application, and you can learn more about it in "Concurrent Programming in Java" by Doug Lea(Especially, chapter 4.1.4 "Worker Threads" would be helpful). Also, you can imagine this kind of mechanism is not unique in Android framework, but all GUI framework may need somewhat similar to this. You can find almost same mechanism in Java Swing framework.

Wordpress keeps redirecting to install-php after migration

I experienced a similar issue. None of the suggestions above helped me, though.

Eventually I realized that the Wordpress MySQL-user on my production environment had not been assigned sufficient privileges.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

For all those who tried everything mentioned above on Windows 7 and still it didn't work, here is what I've done: - open GitBash.exe from the Git directory C:\Program Files (x86)\Git\ (don't open a command prompt, this won't work). - add the following as mentioned above, but you have to delete the #

Host heroku.com
Hostname heroku.com 
Port 22 
IdentitiesOnly yes 
IdentityFile ~/.ssh/ssh-dss
TCPKeepAlive yes 
User [email protected]

now run git push heroku master and it should work.

Java: how to initialize String[]?

String[] errorSoon = { "foo", "bar" };

-- or --

String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

VB.NET: Clear DataGridView

Follow the easy way like this

assume that ta is a DataTable

ta.clear()
DataGridView1.DataSource = ta
DataGridView1.DataSource = Nothing

Delegation: EventEmitter or Observable in Angular

If one wants to follow a more Reactive oriented style of programming, then definitely the concept of "Everything is a stream" comes into picture and hence, use Observables to deal with these streams as often as possible.

How to use NSURLConnection to connect with SSL for an untrusted cert?

With AFNetworking I have successfully consumed https webservice with below code,

NSString *aStrServerUrl = WS_URL;

// Initialize AFHTTPRequestOperationManager...
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES; 
[manager POST:aStrServerUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    successBlock(operation, responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    errorBlock(operation, error);
}];

how to refresh page in angular 2

window.location.reload() or just location.reload()

How to convert int to float in C?

No, because you do the expression using integers, so you divide the integer 50 by the integer 100, which results in the integer 0. Type cast one of them to a float and it should work.

Sorting dropdown alphabetically in AngularJS

You should be able to use filter: orderBy

orderBy can accept a third option for the reverse flag.

<select ng-option="item.name for item in items | orderBy:'name':true"></select>

Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

@see http://docs.angularjs.org/api/ng.filter:orderBy

problem with <select> and :after with CSS in WebKit

<div class="select">
<select name="you_are" id="dropdown" class="selection">
<option value="0" disabled selected>Select</option>
<option value="1">Student</option>
<option value="2">Full-time Job</option>
<option value="2">Part-time Job</option>
<option value="3">Job-Seeker</option>
<option value="4">Nothing Yet</option>
</select>
</div>

Insted of styling the select why dont you add a div out-side the select.

and style then in CSS

.select{
    width: 100%;
    height: 45px;
    position: relative;
}
.select::after{
    content: '\f0d7';
    position: absolute;
    top: 0px;
    right: 10px;
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    color: #0b660b;
    font-size: 45px;
    z-index: 2;

}
#dropdown{
    -webkit-appearance: button;
       -moz-appearance: button;
            appearance: button;
            height: 45px;
            width: 100%;
        outline: none;
        border: none;
        border-bottom: 2px solid #0b660b;
        font-size: 20px;
        background-color: #0b660b23;
        box-sizing: border-box;
        padding-left: 10px;
        padding-right: 10px;
}

How to debug in Django, the good way?

Sometimes when I wan to explore around in a particular method and summoning pdb is just too cumbersome, I would add:

import IPython; IPython.embed()

IPython.embed() starts an IPython shell which have access to the local variables from the point where you call it.

How to select the last record of a table in SQL?

select ADU.itemid, ADU.startdate, internalcostprice 
from ADUITEMINTERNALCOSTPRICE ADU

right join

   (select max(STARTDATE) as Max_date, itemid 
   from ADUITEMINTERNALCOSTPRICE
   group by itemid) as A

on A.ITEMID = ADU.ITEMID
and startdate= Max_date

Extract images from PDF without resampling, in python?

In Python with PyPDF2 and Pillow libraries it is simple:

import PyPDF2

from PIL import Image

if __name__ == '__main__':
    input1 = PyPDF2.PdfFileReader(open("input.pdf", "rb"))
    page0 = input1.getPage(0)
    xObject = page0['/Resources']['/XObject'].getObject()

    for obj in xObject:
        if xObject[obj]['/Subtype'] == '/Image':
            size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
            data = xObject[obj].getData()
            if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                mode = "RGB"
            else:
                mode = "P"

            if xObject[obj]['/Filter'] == '/FlateDecode':
                img = Image.frombytes(mode, size, data)
                img.save(obj[1:] + ".png")
            elif xObject[obj]['/Filter'] == '/DCTDecode':
                img = open(obj[1:] + ".jpg", "wb")
                img.write(data)
                img.close()
            elif xObject[obj]['/Filter'] == '/JPXDecode':
                img = open(obj[1:] + ".jp2", "wb")
                img.write(data)
                img.close()

How to get a tab character?

put it in between <pre></pre> tags then use this characters &#9;

it would not work without the <pre></pre> tags

Difference between object and class in Scala

A class is a definition, a description. It defines a type in terms of methods and composition of other types.

An object is a singleton -- an instance of a class which is guaranteed to be unique. For every object in the code, an anonymous class is created, which inherits from whatever classes you declared object to implement. This class cannot be seen from Scala source code -- though you can get at it through reflection.

There is a relationship between object and class. An object is said to be the companion-object of a class if they share the same name. When this happens, each has access to methods of private visibility in the other. These methods are not automatically imported, though. You either have to import them explicitly, or prefix them with the class/object name.

For example:

class X {
  // class X can see private members of object X
  // Prefix to call
  def m(x: Int) = X.f(x)

  // Import and use
  import X._
  def n(x: Int) = f(x)

  private def o = 2
}

object X {
  private def f(x: Int) = x * x

  // object X can see private members of class X
  def g(x: X) = {
    import x._
    x.o * o // fully specified and imported
   }
}

CodeIgniter - how to catch DB errors?

Use it

    $this->db->_error_message(); 

It is better for finding error.After completing your site. Close the error messages using it

    $db['default']['db_debug'] = FALSE;

You will change it in your config folder's database.php

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

  1. Opened package.json
  2. Changed "@angular-devkit/build-angular": "^0.800.0" to "@angular-devkit/build-angular": "^0.10.0" or changed Changing from "@angular-devkit/build-angular": "^0.802.1" to "@angular-devkit/build-angular": "^0.13.9"
  3. Run npm install
  4. Run ng serve

The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem

jQuery select change event get selected option

You can use the jQuery find method

 $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
 });

The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)

    $('select').find('option').click(function () {
     var optionSelected = $(this);
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
   });

Auto detect mobile browser (via user-agent?)

I put this demo with scripts and examples included together:

http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/

This example utilizes php functions for user agent detection and offers the additional benefit of permitting users to state a preference for a version of the site which would not typically be the default based on their browser or device type. This is done with cookies (maintained using php on the server-side as opposed to javascript.)

Be sure to check out the download link in the article for the examples.

Hope you enjoy!

Find string between two substrings

String formatting adds some flexibility to what Nikolaus Gradwohl suggested. start and end can now be amended as desired.

import re

s = 'asdf=5;iwantthis123jasd'
start = 'asdf=5;'
end = '123jasd'

result = re.search('%s(.*)%s' % (start, end), s).group(1)
print(result)

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

Android Studio doesn't recognize my device

In addition to the above configurations, I had to set deployment target to "Open Select Deployment Target Dialog", run once (choosing my device from the options listed), and from then on Android Studio was able to see my device even after changing the deployment setting back to "USB Device". My SWAG is that since Android Studio uses its own internal cache to find your device, it has to be initialized first.

Permission denied at hdfs

Start a shell as hduser (from root) and run your command

sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input

[update] Also note that the hdfs user is the super user and has all r/w privileges.

Get column from a two dimensional array

You have to loop through each element in the 2d-array, and get the nth column.

    function getCol(matrix, col){
       var column = [];
       for(var i=0; i<matrix.length; i++){
          column.push(matrix[i][col]);
       }
       return column;
    }

    var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
    getCol(array, 0); //Get first column

SQL UPDATE with sub-query that references the same table in MySQL

I needed this for SQL Server. Here it is:

UPDATE user_account 
SET student_education_facility_id = cnt.education_facility_id
from  (
   SELECT user_account_id,education_facility_id
   FROM user_account 
   WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id

I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.

The format I needed was this actually:

UPDATE table1 
SET f1 = cnt.computed_column
from  (
   SELECT id,computed_column --can be any complex subquery
   FROM table1
) as cnt
WHERE cnt.id = table1.id

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

Mocking HttpClient in unit tests

Perhaps there would be some code to change in your current project but for new projects you should absolutely consider using Flurl.

https://flurl.dev

It is a HTTP client library for .NET with a fluent interface that specifically enables testability for code that uses it to make HTTP requests.

There are plenty of code samples on the website but in a nutshell you use it like this in your code.

Add the usings.

using Flurl;
using Flurl.Http;

Send a get request and read the response.

public async Task SendGetRequest()
{
   var response = await "https://example.com".GetAsync();
   // ...
}

In the unit tests Flurl acts as a mock that can be configured to behave as desired and also to verify the calls that were done.

using (var httpTest = new HttpTest())
{
   // Arrange
   httpTest.RespondWith("OK", 200);

   // Act
   await sut.SendGetRequest();

   // Assert
   httpTest.ShouldHaveCalled("https://example.com")
      .WithVerb(HttpMethod.Get);
}

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If You are trying to access it through Data Connections in Visual Studio 2015, and getting the above Error, Then Go to Advanced and set TrustServerCertificate=True for error to go away.

SQL: Group by minimum value in one field while selecting distinct rows

How about something like:

SELECT mt.*     
FROM MyTable mt INNER JOIN
    (
        SELECT id, MIN(record_date) AS MinDate
        FROM MyTable
        GROUP BY id
    ) t ON mt.id = t.id AND mt.record_date = t.MinDate

This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.

How to dynamically allocate memory space for a string and get that string from user?

char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string = '\0';

int key;
int sizer = 2;

char sup[2] = {'\0'};

while( (key = getc(stdin)) != '\n')
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }

Return date as ddmmyyyy in SQL Server

SELECT REPLACE(CONVERT(VARCHAR(10), THEDATE, 103), '/', '') AS [DDMMYYYY]

As seen here: http://www.sql-server-helper.com/tips/date-formats.aspx

How to convert unix timestamp to calendar date moment.js

Might be a little late but for new issues like this I use this code:

moment(timestamp, 'X').format('lll');

You can change the format to match your needs and also add timezone like this:

moment(timestamp, 'X').tz(timezone).format('lll');

java.lang.ClassNotFoundException: HttpServletRequest

I did not have a servlet-api.jar in the application's WEB-INF/lib directory (or any other jar there). The problem was that in WEB-INF/web.xml I had this...

    ...
    <servlet>
      <servlet-name>MyServlet</servlet-name>
      <servlet-class>com.bizooka.net.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>MyServlet</servlet-name>
      <url-pattern>/MyServlet</url-pattern>
    </servlet-mapping>
    ...

...according to a tutorial. Removing that still allowed the servlet to function, and did not get the error.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

Status code '0' can occur because of three reasons
1) The Client cannot connect to the server
2) The Client cannot receive the response within the timeout period
3) The Request was "stopped(aborted)" by the Client.

But these three reasons are not standardized

How do I interpret precision and scale of a number in a database?

Numeric precision refers to the maximum number of digits that are present in the number.

ie 1234567.89 has a precision of 9

Numeric scale refers to the maximum number of decimal places

ie 123456.789 has a scale of 3

Thus the maximum allowed value for decimal(5,2) is 999.99

ProgressDialog is deprecated.What is the alternate one to use?

ProgressDialog was deprecated in API level 26 .

"Deprecated" refers to functions or elements that are in the process of being replaced by newer ones.

ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI.

Advantage

I would personally say that ProgressBar has the edge over the two .ProgressBar is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

How to prettyprint a JSON file?

Use this function and don't sweat having to remember if your JSON is a str or dict again - just look at the pretty print:

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)

Can you test google analytics on a localhost address?

For those using google tag manager to integrate with google analytics events you can do what the guys mentioned about to set the cookies flag to none from GTM it self

enter image description here

open GTM > variables > google analytics variables > and set the cookies tag to none

convert from Color to brush

It's often sufficient to use sibling's or parent's brush for the purpose, and that's easily available in wpf via retrieving their Foreground or Background property.

ref: Control.Background

Laravel: PDOException: could not find driver

I had the same issue, and I uncomment extension=pdo_sqlite and ran the migration and everything worked fine.

How to get query parameters from URL in Angular 5?

I know that OP asked for Angular 5 solution, but yet for all of you who stumbles upon this question for newer (6+) Angular versions. Citing the Docs, regarding ActivatedRoute.queryParams (which most of other answers are based on):

Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.

params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

queryParams — An Observable that contains the query parameters available to all routes. Use queryParamMap instead.

According to the Docs, the simple way to get the query params would look like this:

constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.param1 = this.route.snapshot.paramMap.get('param1');
    this.param2 = this.route.snapshot.paramMap.get('param2');
}

For more advanced ways (e.g. advanced component re-usage) see this Docs chapter.

EDIT:

As it correctly stated in comments below, this answer is wrong - at least for the case specified by OP.

OP asks to get global query parameters (/app?param1=hallo&param2=123); in this case you should use queryParamMap (just like in @dapperdan1985 answer).

paramMap, on the other hand, is used on parameters specific to the route (e.g. /app/:param1/:param2, resulting in /app/hallo/123).

Thanks to @JasonRoyle and @daka for pointing it out.

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to change Java version used by TOMCAT?

There are several good answers on here but I wanted to add one since it may be helpful for users like me who have Tomcat installed as a service on a Windows machine.

Option 3 here: http://www.codejava.net/servers/tomcat/4-ways-to-change-jre-for-tomcat

Basically, open tomcatw.exe and point Tomcat to the version of the JVM you need to use then restart the service. Ensure your deployed applications still work as well.

How to get rid of punctuation using NLTK tokenizer?

You do not really need NLTK to remove punctuation. You can remove it with simple python. For strings:

import string
s = '... some string with punctuation ...'
s = s.translate(None, string.punctuation)

Or for unicode:

import string
translate_table = dict((ord(char), None) for char in string.punctuation)   
s.translate(translate_table)

and then use this string in your tokenizer.

P.S. string module have some other sets of elements that can be removed (like digits).

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Nginx 403 forbidden for all files

Old question, but I had the same issue. I tried every answer above, nothing worked. What fixed it for me though was removing the domain, and adding it again. I'm using Plesk, and I installed Nginx AFTER the domain was already there.

Did a local backup to /var/www/backups first though. So I could easily copy back the files.

Strange problem....

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

Java get String CompareTo as a comparator object

To generalize the good answer of Mike Nakis with String.CASE_INSENSITIVE_ORDER, you can also use :

Collator.getInstance();

See Collator

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

How can foreign key constraints be temporarily disabled using T-SQL?

If you want to disable all constraints in the database just run this code:

-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

To switch them back on, run: (the print is optional of course and it is just listing the tables)

-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

If you are deleting all the data you may find this solution to be helpful.

Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.

What is the JavaScript equivalent of var_dump or print_r in PHP?

As others have already mentioned, the best way to debug your variables is to use a modern browser's developer console (e.g. Chrome Developer Tools, Firefox+Firebug, Opera Dragonfly (which now disappeared in the new Chromium-based (Blink) Opera, but as developers say, "Dragonfly is not dead though we cannot give you more information yet").

But in case you need another approach, there's a really useful site called php.js:

http://phpjs.org/

which provides "JavaScript alternatives to PHP functions" - so you can use them the similar way as you would in PHP. I will copy-paste the appropriate functions to you here, BUT be aware that these codes can get updated on the original site in case some bugs are detected, so I suggest you visiting the phpjs.org site! (Btw. I'm NOT affiliated with the site, but I find it extremely useful.)

var_dump() in JavaScript

Here is the code of the JS-alternative of var_dump():
http://phpjs.org/functions/var_dump/
it depends on the echo() function: http://phpjs.org/functions/echo/

function var_dump() {
  //  discuss at: http://phpjs.org/functions/var_dump/
  // original by: Brett Zamir (http://brett-zamir.me)
  // improved by: Zahlii
  // improved by: Brett Zamir (http://brett-zamir.me)
  //  depends on: echo
  //        note: For returning a string, use var_export() with the second argument set to true
  //        test: skip
  //   example 1: var_dump(1);
  //   returns 1: 'int(1)'

  var output = '',
    pad_char = ' ',
    pad_val = 4,
    lgth = 0,
    i = 0;

  var _getFuncName = function(fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/)
      .exec(fn);
    if (!name) {
      return '(Anonymous)';
    }
    return name[1];
  };

  var _repeat_char = function(len, pad_char) {
    var str = '';
    for (var i = 0; i < len; i++) {
      str += pad_char;
    }
    return str;
  };
  var _getInnerVal = function(val, thick_pad) {
    var ret = '';
    if (val === null) {
      ret = 'NULL';
    } else if (typeof val === 'boolean') {
      ret = 'bool(' + val + ')';
    } else if (typeof val === 'string') {
      ret = 'string(' + val.length + ') "' + val + '"';
    } else if (typeof val === 'number') {
      if (parseFloat(val) == parseInt(val, 10)) {
        ret = 'int(' + val + ')';
      } else {
        ret = 'float(' + val + ')';
      }
    }
    // The remaining are not PHP behavior because these values only exist in this exact form in JavaScript
    else if (typeof val === 'undefined') {
      ret = 'undefined';
    } else if (typeof val === 'function') {
      var funcLines = val.toString()
        .split('\n');
      ret = '';
      for (var i = 0, fll = funcLines.length; i < fll; i++) {
        ret += (i !== 0 ? '\n' + thick_pad : '') + funcLines[i];
      }
    } else if (val instanceof Date) {
      ret = 'Date(' + val + ')';
    } else if (val instanceof RegExp) {
      ret = 'RegExp(' + val + ')';
    } else if (val.nodeName) {
      // Different than PHP's DOMElement
      switch (val.nodeType) {
      case 1:
        if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') {
          // Undefined namespace could be plain XML, but namespaceURI not widely supported
          ret = 'HTMLElement("' + val.nodeName + '")';
        } else {
          ret = 'XML Element("' + val.nodeName + '")';
        }
        break;
      case 2:
        ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')';
        break;
      case 3:
        ret = 'TEXT_NODE(' + val.nodeValue + ')';
        break;
      case 4:
        ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')';
        break;
      case 5:
        ret = 'ENTITY_REFERENCE_NODE';
        break;
      case 6:
        ret = 'ENTITY_NODE';
        break;
      case 7:
        ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue + ')';
        break;
      case 8:
        ret = 'COMMENT_NODE(' + val.nodeValue + ')';
        break;
      case 9:
        ret = 'DOCUMENT_NODE';
        break;
      case 10:
        ret = 'DOCUMENT_TYPE_NODE';
        break;
      case 11:
        ret = 'DOCUMENT_FRAGMENT_NODE';
        break;
      case 12:
        ret = 'NOTATION_NODE';
        break;
      }
    }
    return ret;
  };

  var _formatArray = function(obj, cur_depth, pad_val, pad_char) {
    var someProp = '';
    if (cur_depth > 0) {
      cur_depth++;
    }

    var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char);
    var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char);
    var str = '';
    var val = '';

    if (typeof obj === 'object' && obj !== null) {
      if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') {
        return obj.var_dump();
      }
      lgth = 0;
      for (someProp in obj) {
        lgth++;
      }
      str += 'array(' + lgth + ') {\n';
      for (var key in obj) {
        var objVal = obj[key];
        if (typeof objVal === 'object' && objVal !== null && !(objVal instanceof Date) && !(objVal instanceof RegExp) &&
          !
          objVal.nodeName) {
          str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val,
            pad_char);
        } else {
          val = _getInnerVal(objVal, thick_pad);
          str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n';
        }
      }
      str += base_pad + '}\n';
    } else {
      str = _getInnerVal(obj, thick_pad);
    }
    return str;
  };

  output = _formatArray(arguments[0], 0, pad_val, pad_char);
  for (i = 1; i < arguments.length; i++) {
    output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char);
  }

  this.echo(output);
}

print_r() in JavaScript

Here is the print_r() function:
http://phpjs.org/functions/print_r/
It depends on echo() too.

function print_r(array, return_val) {
  //  discuss at: http://phpjs.org/functions/print_r/
  // original by: Michael White (http://getsprink.com)
  // improved by: Ben Bryan
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Brett Zamir (http://brett-zamir.me)
  //  depends on: echo
  //   example 1: print_r(1, true);
  //   returns 1: 1

  var output = '',
    pad_char = ' ',
    pad_val = 4,
    d = this.window.document,
    getFuncName = function(fn) {
      var name = (/\W*function\s+([\w\$]+)\s*\(/)
        .exec(fn);
      if (!name) {
        return '(Anonymous)';
      }
      return name[1];
    };
  repeat_char = function(len, pad_char) {
    var str = '';
    for (var i = 0; i < len; i++) {
      str += pad_char;
    }
    return str;
  };
  formatArray = function(obj, cur_depth, pad_val, pad_char) {
    if (cur_depth > 0) {
      cur_depth++;
    }

    var base_pad = repeat_char(pad_val * cur_depth, pad_char);
    var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char);
    var str = '';

    if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !==
      'PHPJS_Resource') {
      str += 'Array\n' + base_pad + '(\n';
      for (var key in obj) {
        if (Object.prototype.toString.call(obj[key]) === '[object Array]') {
          str += thick_pad + '[' + key + '] => ' + formatArray(obj[key], cur_depth + 1, pad_val, pad_char);
        } else {
          str += thick_pad + '[' + key + '] => ' + obj[key] + '\n';
        }
      }
      str += base_pad + ')\n';
    } else if (obj === null || obj === undefined) {
      str = '';
    } else {
      // for our "resource" class
      str = obj.toString();
    }

    return str;
  };

  output = formatArray(array, 0, pad_val, pad_char);

  if (return_val !== true) {
    if (d.body) {
      this.echo(output);
    } else {
      try {
        // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
        d = XULDocument;
        this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
      } catch (e) {
        // Outputting as plain text may work in some plain XML
        this.echo(output);
      }
    }
    return true;
  }
  return output;
}

var_export() in JavaScript

You may also find the var_export() alternative useful, which also depends on echo():
http://phpjs.org/functions/var_export/

function var_export(mixed_expression, bool_return) {
  //  discuss at: http://phpjs.org/functions/var_export/
  // original by: Philip Peterson
  // improved by: johnrembo
  // improved by: Brett Zamir (http://brett-zamir.me)
  //    input by: Brian Tafoya (http://www.premasolutions.com/)
  //    input by: Hans Henrik (http://hanshenrik.tk/)
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //  depends on: echo
  //   example 1: var_export(null);
  //   returns 1: null
  //   example 2: var_export({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}, true);
  //   returns 2: "array (\n  0 => 'Kevin',\n  1 => 'van',\n  2 => 'Zonneveld'\n)"
  //   example 3: data = 'Kevin';
  //   example 3: var_export(data, true);
  //   returns 3: "'Kevin'"

  var retstr = '',
    iret = '',
    value,
    cnt = 0,
    x = [],
    i = 0,
    funcParts = [],
    // We use the last argument (not part of PHP) to pass in
    // our indentation level
    idtLevel = arguments[2] || 2,
    innerIndent = '',
    outerIndent = '',
    getFuncName = function(fn) {
      var name = (/\W*function\s+([\w\$]+)\s*\(/)
        .exec(fn);
      if (!name) {
        return '(Anonymous)';
      }
      return name[1];
    };
  _makeIndent = function(idtLevel) {
    return (new Array(idtLevel + 1))
      .join(' ');
  };
  __getType = function(inp) {
    var i = 0,
      match, types, cons, type = typeof inp;
    if (type === 'object' && (inp && inp.constructor) &&
      getFuncName(inp.constructor) === 'PHPJS_Resource') {
      return 'resource';
    }
    if (type === 'function') {
      return 'function';
    }
    if (type === 'object' && !inp) {
      // Should this be just null?
      return 'null';
    }
    if (type === 'object') {
      if (!inp.constructor) {
        return 'object';
      }
      cons = inp.constructor.toString();
      match = cons.match(/(\w+)\(/);
      if (match) {
        cons = match[1].toLowerCase();
      }
      types = ['boolean', 'number', 'string', 'array'];
      for (i = 0; i < types.length; i++) {
        if (cons === types[i]) {
          type = types[i];
          break;
        }
      }
    }
    return type;
  };
  type = __getType(mixed_expression);

  if (type === null) {
    retstr = 'NULL';
  } else if (type === 'array' || type === 'object') {
    outerIndent = _makeIndent(idtLevel - 2);
    innerIndent = _makeIndent(idtLevel);
    for (i in mixed_expression) {
      value = this.var_export(mixed_expression[i], 1, idtLevel + 2);
      value = typeof value === 'string' ? value.replace(/</g, '&lt;')
        .
      replace(/>/g, '&gt;'): value;
      x[cnt++] = innerIndent + i + ' => ' +
        (__getType(mixed_expression[i]) === 'array' ?
          '\n' : '') + value;
    }
    iret = x.join(',\n');
    retstr = outerIndent + 'array (\n' + iret + '\n' + outerIndent + ')';
  } else if (type === 'function') {
    funcParts = mixed_expression.toString()
      .
    match(/function .*?\((.*?)\) \{([\s\S]*)\}/);

    // For lambda functions, var_export() outputs such as the following:
    // '\000lambda_1'. Since it will probably not be a common use to
    // expect this (unhelpful) form, we'll use another PHP-exportable
    // construct, create_function() (though dollar signs must be on the
    // variables in JavaScript); if using instead in JavaScript and you
    // are using the namespaced version, note that create_function() will
    // not be available as a global
    retstr = "create_function ('" + funcParts[1] + "', '" +
      funcParts[2].replace(new RegExp("'", 'g'), "\\'") + "')";
  } else if (type === 'resource') {
    // Resources treated as null for var_export
    retstr = 'NULL';
  } else {
    retstr = typeof mixed_expression !== 'string' ? mixed_expression :
      "'" + mixed_expression.replace(/(["'])/g, '\\$1')
      .
    replace(/\0/g, '\\0') + "'";
  }

  if (!bool_return) {
    this.echo(retstr);
    return null;
  }

  return retstr;
}

echo() in JavaScript

http://phpjs.org/functions/echo/

function echo() {
  //  discuss at: http://phpjs.org/functions/echo/
  // original by: Philip Peterson
  // improved by: echo is bad
  // improved by: Nate
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Brett Zamir (http://brett-zamir.me)
  //  revised by: Der Simon (http://innerdom.sourceforge.net/)
  // bugfixed by: Eugene Bulkin (http://doubleaw.com/)
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: EdorFaus
  //    input by: JB
  //        note: If browsers start to support DOM Level 3 Load and Save (parsing/serializing),
  //        note: we wouldn't need any such long code (even most of the code below). See
  //        note: link below for a cross-browser implementation in JavaScript. HTML5 might
  //        note: possibly support DOMParser, but that is not presently a standard.
  //        note: Although innerHTML is widely used and may become standard as of HTML5, it is also not ideal for
  //        note: use with a temporary holder before appending to the DOM (as is our last resort below),
  //        note: since it may not work in an XML context
  //        note: Using innerHTML to directly add to the BODY is very dangerous because it will
  //        note: break all pre-existing references to HTMLElements.
  //   example 1: echo('<div><p>abc</p><p>abc</p></div>');
  //   returns 1: undefined

  var isNode = typeof module !== 'undefined' && module.exports && typeof global !== "undefined" && {}.toString.call(
    global) == '[object global]';
  if (isNode) {
    var args = Array.prototype.slice.call(arguments);
    return console.log(args.join(' '));
  }

  var arg = '';
  var argc = arguments.length;
  var argv = arguments;
  var i = 0;
  var holder, win = this.window;
  var d = win.document;
  var ns_xhtml = 'http://www.w3.org/1999/xhtml';
  // If we're in a XUL context
  var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';

  var stringToDOM = function(str, parent, ns, container) {
    var extraNSs = '';
    if (ns === ns_xul) {
      extraNSs = ' xmlns:html="' + ns_xhtml + '"';
    }
    var stringContainer = '<' + container + ' xmlns="' + ns + '"' + extraNSs + '>' + str + '</' + container + '>';
    var dils = win.DOMImplementationLS;
    var dp = win.DOMParser;
    var ax = win.ActiveXObject;
    if (dils && dils.createLSInput && dils.createLSParser) {
      // Follows the DOM 3 Load and Save standard, but not
      // implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
      // possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
      // attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
      var lsInput = dils.createLSInput();
      // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
      lsInput.stringData = stringContainer;
      // synchronous, no schema type
      var lsParser = dils.createLSParser(1, null);
      return lsParser.parse(lsInput)
        .firstChild;
    } else if (dp) {
      // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
      try {
        var fc = new dp()
          .parseFromString(stringContainer, 'text/xml');
        if (fc && fc.documentElement && fc.documentElement.localName !== 'parsererror' && fc.documentElement.namespaceURI !==
          'http://www.mozilla.org/newlayout/xml/parsererror.xml') {
          return fc.documentElement.firstChild;
        }
        // If there's a parsing error, we just continue on
      } catch (e) {
        // If there's a parsing error, we just continue on
      }
    } else if (ax) {
      // We don't bother with a holder in Explorer as it doesn't support namespaces
      var axo = new ax('MSXML2.DOMDocument');
      axo.loadXML(str);
      return axo.documentElement;
    }
    /*else if (win.XMLHttpRequest) {
     // Supposed to work in older Safari
      var req = new win.XMLHttpRequest;
      req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false);
      if (req.overrideMimeType) {
        req.overrideMimeType('application/xml');
      }
      req.send(null);
      return req.responseXML;
    }*/
    // Document fragment did not work with innerHTML, so we create a temporary element holder
    // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
    //if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) {
    // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways)
    if (d.createElementNS && // Browser supports the method
      (d.documentElement.namespaceURI || // We can use if the document is using a namespace
        d.documentElement.nodeName.toLowerCase() !== 'html' || // We know it's not HTML4 or less, if the tag is not HTML (even if the root namespace is null)
        (d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace
      )) {
      // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document
      holder = d.createElementNS(ns, container);
    } else {
      // Document fragment did not work with innerHTML
      holder = d.createElement(container);
    }
    holder.innerHTML = str;
    while (holder.firstChild) {
      parent.appendChild(holder.firstChild);
    }
    return false;
    // throw 'Your browser does not support DOM parsing as required by echo()';
  };

  var ieFix = function(node) {
    if (node.nodeType === 1) {
      var newNode = d.createElement(node.nodeName);
      var i, len;
      if (node.attributes && node.attributes.length > 0) {
        for (i = 0, len = node.attributes.length; i < len; i++) {
          newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
        }
      }
      if (node.childNodes && node.childNodes.length > 0) {
        for (i = 0, len = node.childNodes.length; i < len; i++) {
          newNode.appendChild(ieFix(node.childNodes[i]));
        }
      }
      return newNode;
    } else {
      return d.createTextNode(node.nodeValue);
    }
  };

  var replacer = function(s, m1, m2) {
    // We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.)
    // Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
    if (m1 !== '\\') {
      return m1 + eval(m2);
    } else {
      return s;
    }
  };

  this.php_js = this.php_js || {};
  var phpjs = this.php_js;
  var ini = phpjs.ini;
  var obs = phpjs.obs;
  for (i = 0; i < argc; i++) {
    arg = argv[i];
    if (ini && ini['phpjs.echo_embedded_vars']) {
      arg = arg.replace(/(.?)\{?\$(\w*?\}|\w*)/g, replacer);
    }

    if (!phpjs.flushing && obs && obs.length) {
      // If flushing we output, but otherwise presence of a buffer means caching output
      obs[obs.length - 1].buffer += arg;
      continue;
    }

    if (d.appendChild) {
      if (d.body) {
        if (win.navigator.appName === 'Microsoft Internet Explorer') {
          // We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended
          d.body.appendChild(stringToDOM(ieFix(arg)));
        } else {
          var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div')
            .cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default)
          if (unappendedLeft) {
            d.body.appendChild(unappendedLeft);
          }
        }
      } else {
        // We will not actually append the description tag (just using for providing XUL namespace by default)
        d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description'));
      }
    } else if (d.write) {
      d.write(arg);
    } else {
      console.log(arg);
    }
  }
}

how to define variable in jquery

You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();

Regular Expression for any number greater than 0?

I think the best solution is to add the + sign between the two brackets of regex expression:

^[1-9]+[0-9]*$

What do the icons in Eclipse mean?

I can't find a way to create a table with icons in SO, so I am uploading 2 images. Objects Icons

Decorator icons

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

How do I use an image as a submit button?

Just remove the border and add a background image in css

Example:

_x000D_
_x000D_
$("#form").on('submit', function() {_x000D_
   alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
  background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
  background-size: cover;_x000D_
  border: none;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  cursor: pointer;_x000D_
  color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Unicode character in PHP string

PHP 7.0.0 has introduced the "Unicode codepoint escape" syntax.

It's now possible to write Unicode characters easily by using a double-quoted or a heredoc string, without calling any function.

$unicodeChar = "\u{1000}";

Oracle: Import CSV file

Another solution you can use is SQL Developer.

With it, you have the ability to import from a csv file (other delimited files are available).

Just open the table view, then:

  • choose actions
  • import data
  • find your file
  • choose your options.

You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).

Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).

Just adding another option to the 2 already very good answers.

Multiple distinct pages in one HTML file

Let's say you have multiple pages, with id #page1 #page2 and #page3. #page1 is the ID of your start page. The first thing you want to do is to redirect to your start page each time the webpage is loading. You do this with javascript:

document.location.hash = "#page1";

Then the next thing you want to do is place some links in your document to the different pages, like for example:

<a href="#page2">Click here to get to page 2.</a>

Then, lastly, you'd want to make sure that only the active page, or target-page is visible, and all other pages stay hidden. You do this with the following declarations in the <style> element:

<style>
#page1 {display:none}
#page1:target {display:block}
#page2 {display:none}
#page2:target {display:block}
#page3 {display:none}
#page3:target {display:block}
</style>

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Split Java String by New Line

String#split?(String regex) method is using regex (regular expressions). Since Java 8 regex supports \R which represents (from documentation of Pattern class):

Linebreak matcher
\R         Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

So we can use it to match:

As you see \r\n is placed at start of regex which ensures that regex will try to match this pair first, and only if that match fails it will try to match single character line separators.


So if you want to split on line separator use split("\\R").

If you don't want to remove from resulting array trailing empty strings "" use split(regex, limit) with negative limit parameter like split("\\R", -1).

If you want to treat one or more continues empty lines as single delimiter use split("\\R+").

Which command do I use to generate the build of a Vue app?

The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

If you are looking to run your site locally, you can test it with

npm serve

If you are looking to prep your site for production, you would use

npm build

This command will generate a dist folder that has a compressed version of your site.

How do I do a Date comparison in Javascript?

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Fix CSS hover on iPhone/iPad/iPod

On some sites I need to use css "cursor:help". Only iOS it gave me a lot of irritation. To solve this, change everything af the page to "cursor:pointer". That works for me.

jQuery:

if (/iP(hone|od|ad)/.test(navigator.platform)) {
$("*").css({"cursor":"pointer"});
}

Loop and get key/value pair for JSON array using jQuery

Parse the JSON string and you can loop through the keys.

_x000D_
_x000D_
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';_x000D_
var data = JSON.parse(resultJSON);_x000D_
_x000D_
for (var key in data)_x000D_
{_x000D_
    //console.log(key + ' : ' + data[key]);_x000D_
    alert(key + ' --> ' + data[key]);_x000D_
}
_x000D_
_x000D_
_x000D_

Calculate a Running Total in SQL Server

If you are using Sql server 2008 R2 above. Then, It would be shortest way to do;

Select id
    ,somedate
    ,somevalue,
LAG(runningtotal) OVER (ORDER BY somedate) + somevalue AS runningtotal
From TestTable 

LAG is use to get previous row value. You can do google for more info.

[1]:

How can I get enum possible values in a MySQL database?

Here is a solution for a custom WordPress table. This will work for ENUM values without a comma (,) in them

function get_enum_values($wpdb, $table, $field) {

    $values = array();
    $table = "{$wpdb->prefix}{$table}";
    $query = "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'";
    $results = $wpdb->get_results($query, ARRAY_A);

    if (is_array($results) && count($results) > 0) {

        preg_match("/^enum\(\'(.*)\'\)$/", $results[0]['Type'], $matches);

        if (is_array($matches) && isset($matches[1])) {

            $values = explode("','", $matches[1]);

        }

    }

    return $values;

}

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

How to do a GitHub pull request

The Simplest GitHub Pull Request is from the web interface without using git.

  1. Register a GitHub account, login then go to the page in the repository you want to change.
  2. Click the pencil icon,

    search for text near the location, make any edits you want then preview them to confirm. Give the proposed change a description up to 50 characters and optionally an extended description then click the Propose file Change button.

  3. If you're reading this you won't have write access to the repository (project folders) so GitHub will create a copy of the repository (actually a branch) in your account. Click the Create pull request button.

  4. Give the Pull Request a description and add any comments then click Create pull request button.

Run a .bat file using python code

This has already been answered in detail on SO. Check out this thread, It should answer all your questions: Executing a subprocess fails

I've tried it myself with this code:

batchtest.py

from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()

batch.bat

echo Hello World!
pause

I've got the batchtest.py example from the aforementioned thread.

How can I change the font-size of a select option?

select[value="value"]{
   background-color: red;
   padding: 3px;
   font-weight:bold;
}

Is PowerShell ready to replace my Cygwin shell on Windows?

TL;DR -- I don't hate Windows or PowerShell. I just can't do anything in Windows or on PowerShell.


I personally still find PowerShell underwhelming at best.

  • tab completion of directory paths do not compound, requiring the user to enter a path separator after every name completion.
  • I still feel like Windows doesn't even have the concept of a path or of what a path is, with no accessible user home indicator ~/ short of some @environment://somejibberish/%user_home%
  • NTFS is still a mess and seemingly always will be. Good luck navigating.

  • cmd-esque interface, The dinosaur cmd.exe is still visible in PowerShell, EditMark still being the only way to copy information, and copying only in the form of rectangular blocks of visible terminal space. and EditMark still being the only way to paste strings into the terminal.

  • Painting it blue doesn't make it any more attractive. I don't mind Microsoft developers having a taste in color though.

  • Windows always opens at top left corner of screen. For somebody who uses vertical task bars this is incredibly annoying, especially considering that the Windows task bar will cover the only corner of the window that gives access to copy/paste functionality.

I can't speak much on the grounds of the tools Windows includes. Being that there is a whole set of open-source, freely licensed CLI tools, and PowerShell ships with, to my knowledge, none of them is an utter disappointment.

  • PowerShell's wget takes seemingly incomparable arguments to GNU wget. Thanks, glimmer of hope portably-useless.
  • PowerShell POSIX is not Bash-compatible, particularly the && operator is not handled, making the simplest of conditional command following not a thing.

I don't know man; I gave it a shot, I really did; I still try to give it a shot in the hopes that the next time I open it it will be any less useless. I cannot do anything in PowerShell, and I can barely do things with a real project to bring GNU tools to Windows.

MySysGit gives me the dinosaur cmd.exe prompt with a couple of GNU tools, and it is still very underwhelming, but at last path completion works. And the Git command will run in Git Bash.

Mintty for MySysGit gives the Cygwin interface over mysysgit's environment, making copy and paste a thing (select to copy (mouse), Shift+Ins to paste, how modern...). However, things like git push are broken in Mintty.

I don't mean to rant, but I still see huge problems with command-line usability on Windows even given tools like Cygwin.


P.S.: Just because something can be done in PowerShell, doesn't make it usable. Usability is deeper than ability and is what I tend to focus on when trying to use a product as a consumer.

Make a phone call programmatically

In Swift 3.0,

static func callToNumber(number:String) {

        let phoneFallback = "telprompt://\(number)"
        let fallbackURl = URL(string:phoneFallback)!

        let phone = "tel://\(number)"
        let url = URL(string:phone)!

        let shared = UIApplication.shared

        if(shared.canOpenURL(fallbackURl)){
            shared.openURL(fallbackURl)
        }else if (shared.canOpenURL(url)){
            shared.openURL(url)
        }else{
            print("unable to open url for call")
        }

    }

Reverse a string without using reversed() or [::-1]?

reduce(lambda x, y : y + x, "hello world")

How to insert an item at the beginning of an array in PHP?

With custom index:

$arr=array("a"=>"one", "b"=>"two");
    $arr=array("c"=>"three", "d"=>"four").$arr;

    print_r($arr);
    -------------------
    output:
    ----------------
    Array
    (
    [c]=["three"]
    [d]=["four"]
    [a]=["two"]
    [b]=["one"]
    )

SQL Server tables: what is the difference between @, # and ##?

# and ## tables are actual tables represented in the temp database. These tables can have indexes and statistics, and can be accessed across sprocs in a session (in the case of a global temp table, it is available across sessions).

The @table is a table variable.

For more: http://www.sqlteam.com/article/temporary-tables

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

How do I properly clean up Excel interop objects?

You can actually release your Excel Application object cleanly, but you do have to take care.

The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via Marshal.FinalReleaseComObject() is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a for each loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.

The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call GC.Collect() and then GC.WaitForPendingFinalizers() to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference.

You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.

For example, assuming that you had a Range object variable named xlRng, a Worksheet variable named xlSheet, a Workbook variable named xlBook and an Excel Application variable named xlApp, then your cleanup code could look something like the following:

// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);

xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);

In most code examples you'll see for cleaning up COM objects from .NET, the GC.Collect() and GC.WaitForPendingFinalizers() calls are made TWICE as in:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the next garbage collection. However, if you are not using VSTO, you should be able to call GC.Collect() and GC.WaitForPendingFinalizers() just once.

I know that explicitly calling GC.Collect() is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling GC.Collect().

This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)

I have a tutorial on this here:

Automating Office Programs with VB.Net / COM Interop

It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

Provided answers are good, but I think they can be improved by adding an "architectural" perspective.

Investigation

MVC's Controller.Json function is doing the job, but it is very poor at providing a relevant error in this case. By using Newtonsoft.Json.JsonConvert.SerializeObject, the error specifies exactly what is the property that is triggering the circular reference. This is particularly useful when serializing more complex object hierarchies.

Proper architecture

One should never try to serialize data models (e.g. EF models), as ORM's navigation properties is the road to perdition when it comes to serialization. Data flow should be the following:

Database -> data models -> service models -> JSON string 

Service models can be obtained from data models using auto mappers (e.g. Automapper). While this does not guarantee lack of circular references, proper design should do it: service models should contain exactly what the service consumer requires (i.e. the properties).

In those rare cases, when the client requests a hierarchy involving the same object type on different levels, the service can create a linear structure with parent->child relationship (using just identifiers, not references).

Modern applications tend to avoid loading complex data structures at once and service models should be slim. E.g.:

  1. access an event - only header data (identifier, name, date etc.) is loaded -> service model (JSON) containing only header data
  2. managed attendees list - access a popup and lazy load the list -> service model (JSON) containing only the list of attendees

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

How to manually trigger validation with jQuery validate?

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

Python loop counter in a for loop

You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

How to return a struct from a function in C++?

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

Unlink of file Failed. Should I try again?

Worked for me, Tried on windows:

Stop your server running from IDE or close your IDE

Intellij/Ecllipse or any, it will work.

How to get folder path for ClickOnce application

ApplicationDeployment.CurrentDeployment.ActivationUri might work

"A zero-length string if the TrustUrlParameters property in the deployment manifest is false, or if the user has supplied a UNC to open the deployment or has opened it locally. Otherwise, the return value is the full URL used to launch the application, including any parameters."


BUT what I think you really want is ApplicationDeployment.CurrentDeployment.DataDirectory which gives you a folder you can write data to. When you update the application anyways you'll lose what was in the original .exe folder, but you can migrate the data directory over to a new version of the app. Your app can write to this folder with whatever log files it has - and I'm pretty sure its guaranteed to be writable.

TypeError: $.ajax(...) is not a function?

This is too late for an answer but this response may be helpful for future readers.

I would like to share a scenario where, say there are multiple html files(one base html and multiple sub-HTMLs) and $.ajax is being used in one of the sub-HTMLs.

Suppose in the sub-HTML, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" and in the base/parent HTML, via URL -"https://code.jquery.com/jquery-3.1.1.slim.min.js", then the slim version of JS will be used across all pages which use this sub-HTML as well as the base HTML mentioned above.

This is especially true in case of using bootstrap framework which loads js using "https://code.jquery.com/jquery-3.1.1.slim.min.js".

So to resolve the problem, need to ensure that in all pages, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" or whatever is the latest URL containing all JQuery libraries.

Thanks to Lily H. for pointing me towards this answer.

How do you move a file?

Subversion has native support for moving files.

svn move SOURCE DESTINATION

See the online help (svn help move) for more information.

How to detect installed version of MS-Office?

Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.

As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.

After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext.

So, my logic follows below:

Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing.

Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume)

Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail(which is also a product ID) along with some other values.

The possible productIds are provided here.

To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext and try to see if any name has a prefix o365, if it finds it then its O365. If it does not, then its Office 2019.

Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.

Hope this will help whoever's interest.

How do I increase the contrast of an image in Python OpenCV

img = cv2.imread("/x2.jpeg")

image = cv2.resize(img, (1800, 1800))

alpha=1.5
beta=20

new_image=cv2.addWeighted(image,alpha,np.zeros(image.shape, image.dtype),0,beta)

cv2.imshow("new",new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

How do I set the figure title and axes labels font size in Matplotlib?

If you're more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

I don't know of a similar way to set the suptitle size after it's created.

How to read a text file in project's root directory?

private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

The method above will bring you something like this:

"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"

From here you can navigate backwards using System.IO.Directory.GetParent:

_filePath = Directory.GetParent(_filePath).FullName;

1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:

_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;

Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:

_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);

Hope it helps.

Remove a marker from a GoogleMap

Create array with all markers on add in map.

Later, use:

Marker temp = markers.get(markers.size() - 1);
temp.remove();

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I resolved this issue by adding jackson-json data binding to my pom.

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
</dependency>

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

Is there a way to take a screenshot using Java and save it to some sort of image?

public void captureScreen(String fileName) throws Exception {
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));
}

How to get primary key column in Oracle?

Save the following script as something like findPK.sql.

set verify off
accept TABLE_NAME char prompt 'Table name>'

SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');

It can then be called using

@findPK

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.

By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.

Hope that helps.

How do I run a program with commandline arguments using GDB within a Bash script?

You can run gdb with --args parameter,

gdb --args executablename arg1 arg2 arg3

If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.

gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3

move div with CSS transition

This may be the good solution for you: change the code like this very little change

.box{
    position: relative; 
}
.box:hover .hidden{
    opacity: 1;
    width:500px;
}
.box .hidden{
    background: yellow;
    height: 334px; 
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    opacity: 0;
    transition: all 1s ease;
}

See demo here

How can I tell jackson to ignore a property for which I don't have control over the source code?

Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

How to convert a string to number in TypeScript?

Call the function with => convertstring('10.00')

parseFloat(string) => It can be used to convert to float, toFixed(4) => to how much decimals

parseInt(str) => It can be used to convert to integer

convertstring(string){
    let number_parsed: any = parseFloat(string).toFixed(4)
    return number_parsed
}

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

In my case I was getting latin cross sign instead of nbsp, even that a page was correctly encoded into the UTF-8. Nothing of above helped in resolving the issue and I tried all.

In the end changing font for IE (with browser specific css) helped, I was using Helvetica-Nue as a body font changing to the Arial resolved the issue .

How to force a view refresh without having it trigger automatically from an observable?

You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated() to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.

H.264 file size for 1 hr of HD video

It is whatever size you want it to be, the only thing that changes is quality. If you intend it to be played back on a non-PC device (or a slow PC), you may need to respect a certain profile (standardized set of compression settings that ensure a fixed device can play back the content).

You can see the main H.264 profiles at Wikipedia

While it is highly subjective (and highly dependent on the content being compressed), it is claimed that H.264 can achieve the same quality as DVD MPEG2 using half the bitrate.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

Very simple example and it always works.

/**
 * Setup stretch and scrollable TabLayout.
 * The TabLayout initial parameters in layout must be:
 * android:layout_width="wrap_content"
 * app:tabMaxWidth="0dp"
 * app:tabGravity="fill"
 * app:tabMode="fixed"
 *
 * @param context   your Context
 * @param tabLayout your TabLayout
 */
public static void setupStretchTabLayout(Context context, TabLayout tabLayout) {
    tabLayout.post(() -> {

        ViewGroup.LayoutParams params = tabLayout.getLayoutParams();
        if (params.width == ViewGroup.LayoutParams.MATCH_PARENT) { // is already set up for stretch
            return;
        }

        int deviceWidth = context.getResources()
                                 .getDisplayMetrics().widthPixels;

        if (tabLayout.getWidth() < deviceWidth) {
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        } else {
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        }
        tabLayout.setLayoutParams(params);

    });

}

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

This is how i solve my problem

let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)



    Alamofire.upload(
        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")


    }, to: "http://platform.twitone.com/station/add-feedback") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print(response.result.value)
            }

        case .failure(let encodingError): break
            print(encodingError)
        }


    }

Django Forms: if not valid, show form with error message

simply you can do like this because when you initialized the form in contains form data and invalid data as well:

def some_func(request):
    form = MyForm(request.POST)
    if form.is_valid():
         //other stuff
    return render(request,template_name,{'form':form})

if will raise the error in the template if have any but the form data will still remain as :

error_demo_here

Table with fixed header and fixed column on pure css

Position : sticky doesn't work for some elements like (thead) in chrome and other webkit browsers like safari.

But it works fine with (th)

_x000D_
_x000D_
body {_x000D_
  background-color: rgba(0, 255, 200, 0.1);_x000D_
}_x000D_
_x000D_
.intro {_x000D_
  color: rgb(228, 23, 23);_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  overflow-y: scroll;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
.sticky {_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
  color: black;_x000D_
  background-color: white;_x000D_
}
_x000D_
<div class="container intro">_x000D_
  <h1>Sticky Table Header</h1>_x000D_
  <p>Postion : sticky doesn't work for some elements like (thead) in chrome and other webkit browsers like safari. </p>_x000D_
  <p>But it works fine with (th)</p>_x000D_
</div>_x000D_
<div class="container wrapper">_x000D_
  <table class="table table-striped">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th class="sticky">Firstname</th>_x000D_
        <th class="sticky">Lastname</th>_x000D_
        <th class="sticky">Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>James</td>_x000D_
        <td>Vince</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Jonny</td>_x000D_
        <td>Bairstow</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>James</td>_x000D_
        <td>Anderson</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Stuart</td>_x000D_
        <td>Broad</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Eoin</td>_x000D_
        <td>Morgan</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Root</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Chris</td>_x000D_
        <td>Woakes</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Liam</td>_x000D_
        <td>PLunkett</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Jason</td>_x000D_
        <td>Roy</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Alex</td>_x000D_
        <td>Hales</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Jos</td>_x000D_
        <td>Buttler</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Ben</td>_x000D_
        <td>Stokes</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Jofra</td>_x000D_
        <td>Archer</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Mitchell</td>_x000D_
        <td>Starc</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Aaron</td>_x000D_
        <td>Finch</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>David</td>_x000D_
        <td>Warner</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Steve</td>_x000D_
        <td>Smith</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Glenn</td>_x000D_
        <td>Maxwell</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Marcus</td>_x000D_
        <td>Stoinis</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Alex</td>_x000D_
        <td>Carey</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Nathan</td>_x000D_
        <td>Coulter Nile</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Pat</td>_x000D_
        <td>Cummins</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Adam</td>_x000D_
        <td>Zampa</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or visit my codepen example :

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

How to randomize (or permute) a dataframe rowwise and columnwise?

You can also "sample" the same number of items in your data frame with something like this:

nr<-dim(M)[1]
random_M = M[sample.int(nr),]

Is there a "between" function in C#?

Or if you want to bound the value to the interval:

public static T EnsureRange<T>(this T value, T min, T max) where T : IComparable<T>
    {
        if (value.CompareTo(min) < 0)
            return min;
        else if (value.CompareTo(max) > 0)
            return max;
        else
            return value;
    }

It is like two-sided Math.Min/Max

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

How do I rewrite URLs in a proxy response in NGINX

We should first read the documentation on proxy_pass carefully and fully.

The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /. Absense of trailing slash means hat URI is absent.

Proxy_pass with URI:

location /some_dir/ {
    proxy_pass http://some_server/;
}

With the above, there's the following proxy:

http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/          some_subdir/some_file

Basically, /some_dir/ gets replaced by / to change the request path from /some_dir/some_subdir/some_file to /some_subdir/some_file.

Proxy_pass without URI:

location /some_dir/ {
    proxy_pass http://some_server;
}

With the second (no trailing slash): the proxy goes like this:

http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file

Basically, the full original request path gets passed on without changes.


So, in your case, it seems you should just drop the trailing slash to get what you want.


Caveat

Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:

location /some_dir/ {
  rewrite    /some_dir/(.*) /$1 break;
  proxy_pass $upstream_server;
}

There are other cases where rewrite wouldn't work, that's why reading documentation is a must.


Edit

Reading your question again, it seems I may have missed that you just want to edit the html output.

For that, you can use the sub_filter directive. Something like ...

location /admin/ {
    proxy_pass http://localhost:8080/;
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

Basically, the string you want to replace and the replacement string

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

How to get the value of an input field using ReactJS?

// On the state
constructor() {
  this.state = {
   email: ''
 }
}

// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}

<Input 
  value={this.state.email ? this.state.email : ''} 
  onChange={event => this.setState({ email: event.target.value)}
  type="text" 
  name="emailAddress" 
  placeholder="[email protected]" />

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error in Chrome. The Chrome console told me that the error was in the 1st line of the HTML file.

It was actually in the .js file. So watch out for setValidNou(1060, $(this).val(), 0') error types.

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

vertical-align: middle doesn't work

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>