Programs & Examples On #Beast

How can I trigger the click event of another element in ng-click using angularjs?

So it was a simple fix. Just had to move the ng-click to a scope click handler:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="clickUpload()">Upload</button>



$scope.clickUpload = function(){
    angular.element('#upload').trigger('click');
};

How can I make my website's background transparent without making the content (images & text) transparent too?

I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8

The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:

filter:Alpha(opacity=50)

Get the client's IP address in socket.io

From reading the socket.io source code it looks like the "listen" method takes arguments (server, options, fn) and if "server" is an instance of an HTTP/S server it will simply wrap it for you.

So you could presumably give it an empty server which listens for the 'connection' event and handles the socket remoteAddress; however, things might be very difficult if you need to associate that address with an actual socket.io Socket object.

var http = require('http')
  , io = require('socket.io');
io.listen(new http.Server().on('connection', function(sock) {
  console.log('Client connected from: ' + sock.remoteAddress);
}).listen(80));

Might be easier to submit a patch to socket.io wherein their own Socket object is extended with the remoteAddress property assigned at connection time...

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

HTML/CSS: how to put text both right and left aligned in a paragraph

Least amount of markup possible (you only need one span):

<p>This text is left. <span>This text is right.</span></p>

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.

The full HTML:

<p class="split-para">This text is left. <span>This text is right.</span></p>

And the CSS:

.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}

ExecutorService that interrupts tasks after a timeout

What about this alternative idea :

  • two have two executors :
    • one for :
      • submitting the task, without caring about the timeout of the task
      • adding the Future resulted and the time when it should end to an internal structure
    • one for executing an internal job which is checking the internal structure if some tasks are timeout and if they have to be cancelled.

Small sample is here :

public class AlternativeExecutorService 
{

private final CopyOnWriteArrayList<ListenableFutureTask> futureQueue       = new CopyOnWriteArrayList();
private final ScheduledThreadPoolExecutor                scheduledExecutor = new ScheduledThreadPoolExecutor(1); // used for internal cleaning job
private final ListeningExecutorService                   threadExecutor    = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)); // used for
private ScheduledFuture scheduledFuture;
private static final long INTERNAL_JOB_CLEANUP_FREQUENCY = 1000L;

public AlternativeExecutorService()
{
    scheduledFuture = scheduledExecutor.scheduleAtFixedRate(new TimeoutManagerJob(), 0, INTERNAL_JOB_CLEANUP_FREQUENCY, TimeUnit.MILLISECONDS);
}

public void pushTask(OwnTask task)
{
    ListenableFuture<Void> future = threadExecutor.submit(task);  // -> create your Callable
    futureQueue.add(new ListenableFutureTask(future, task, getCurrentMillisecondsTime())); // -> store the time when the task should end
}

public void shutdownInternalScheduledExecutor()
{
    scheduledFuture.cancel(true);
    scheduledExecutor.shutdownNow();
}

long getCurrentMillisecondsTime()
{
    return Calendar.getInstance().get(Calendar.MILLISECOND);
}

class ListenableFutureTask
{
    private final ListenableFuture<Void> future;
    private final OwnTask                task;
    private final long                   milliSecEndTime;

    private ListenableFutureTask(ListenableFuture<Void> future, OwnTask task, long milliSecStartTime)
    {
        this.future = future;
        this.task = task;
        this.milliSecEndTime = milliSecStartTime + task.getTimeUnit().convert(task.getTimeoutDuration(), TimeUnit.MILLISECONDS);
    }

    ListenableFuture<Void> getFuture()
    {
        return future;
    }

    OwnTask getTask()
    {
        return task;
    }

    long getMilliSecEndTime()
    {
        return milliSecEndTime;
    }
}

class TimeoutManagerJob implements Runnable
{
    CopyOnWriteArrayList<ListenableFutureTask> getCopyOnWriteArrayList()
    {
        return futureQueue;
    }

    @Override
    public void run()
    {
        long currentMileSecValue = getCurrentMillisecondsTime();
        for (ListenableFutureTask futureTask : futureQueue)
        {
            consumeFuture(futureTask, currentMileSecValue);
        }
    }

    private void consumeFuture(ListenableFutureTask futureTask, long currentMileSecValue)
    {
        ListenableFuture<Void> future = futureTask.getFuture();
        boolean isTimeout = futureTask.getMilliSecEndTime() >= currentMileSecValue;
        if (isTimeout)
        {
            if (!future.isDone())
            {
                future.cancel(true);
            }
            futureQueue.remove(futureTask);
        }
    }
}

class OwnTask implements Callable<Void>
{
    private long     timeoutDuration;
    private TimeUnit timeUnit;

    OwnTask(long timeoutDuration, TimeUnit timeUnit)
    {
        this.timeoutDuration = timeoutDuration;
        this.timeUnit = timeUnit;
    }

    @Override
    public Void call() throws Exception
    {
        // do logic
        return null;
    }

    public long getTimeoutDuration()
    {
        return timeoutDuration;
    }

    public TimeUnit getTimeUnit()
    {
        return timeUnit;
    }
}
}

Objective-C for Windows

If you are comfortable with Visual Studio environment,

Small project: jGRASP with gcc Large project: Cocotron

I heard there are emulators, but I could find only Apple II Emulator http://virtualapple.org/. It looks like limited to games.

Github: error cloning my private repository

I have seen this on Windows, with msysgit 1.7.2.3. You have to fix the path to bin/curl-ca-bundle.crt. I had to specify the absolute path, using back-slashes:

git config --system http.sslcainfo "C:\Program Files (x86)\git\bin\curl-ca-bundle.crt"

This will result in changes to [git-install-dir]/etc/gitconfig file, which may be edited directly, too.

(Original solutions found at http://github.com/blog/642-smart-http-support)

Is it good practice to use the xor operator for boolean checks?

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.

How do I request and receive user input in a .bat and use it to run a certain program?

I have improved batch file with yes or no prompt. If user enter any character except y and n , then it will again prompt user for valid input. It Works for me.

    @echo off

    :ConfirmBox 
        set /P c= Are you sure want to contine (y/n)?

    if /I "%c%" EQU "Y" (
    goto :FnYes 
    ) else if /I "%c%" EQU "N" ( 
    goto :FnNo
    ) else ( 
    goto :InValid 
    )


:FnYes
     echo You have entered Y
     goto :END

:FnNo
     echo You have entered N
     goto :END

:InValid
     echo Invalid selection. Enter Y or N
     goto :ConfirmBox

:END
    pause
    exit  

/I in if condition will validate both lowercase and uppercase characters.

Bytes of a string in Java

According to How to convert Strings to and from UTF8 byte arrays in Java:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

Is there a Python caching library?

import time

class CachedItem(object):
    def __init__(self, key, value, duration=60):
        self.key = key
        self.value = value
        self.duration = duration
        self.timeStamp = time.time()

    def __repr__(self):
        return '<CachedItem {%s:%s} expires at: %s>' % (self.key, self.value, time.time() + self.duration)

class CachedDict(dict):

    def get(self, key, fn, duration):
        if key not in self \
            or self[key].timeStamp + self[key].duration < time.time():
                print 'adding new value'
                o = fn(key)
                self[key] = CachedItem(key, o, duration)
        else:
            print 'loading from cache'

        return self[key].value



if __name__ == '__main__':

    fn = lambda key: 'value of %s  is None' % key

    ci = CachedItem('a', 12)
    print ci 
    cd = CachedDict()
    print cd.get('a', fn, 5)
    time.sleep(2)
    print cd.get('a', fn, 6)
    print cd.get('b', fn, 6)
    time.sleep(2)
    print cd.get('a', fn, 7)
    print cd.get('b', fn, 7)

Using %s in C correctly - very basic level

%s is the representation of an array of char

char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map

character = 'a'; // assign 'a' to character
printf("character %c  ",a); //we will display 'a' to stout

so string is an array of char we can assign multiple character per space of memory

string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends

this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

toy can also assign values to the array of chars assigning it with functions like strcpy;

strcpy(string,"hello" );

this do the same as the example and automatically add the (char) 0 at the end

so if you print it with %S printf("my string %s",string);

and how string is a array we can just display part of it

//                         the array    one char
printf("first letter of wrd %s     is    :%c ",string,string[1]  );

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:

  • https://github.com/facebook/facebook-android-sdk.git
  • git://github.com/facebook/facebook-android-sdk.git

How to submit a form with JavaScript by clicking a link?

If you use jQuery and would need an inline solution, this would work very well;

<a href="#" onclick="$(this).closest('form').submit();">submit form</a>

Also, you might want to replace

<a href="#">text</a>

with

<a href="javascript:void(0);">text</a>

so the user does not scroll to the top of your page when clicking the link.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Restarted the Device, Worked! :D

Thanks Everyone for the great suggestions.

How to kill a nodejs process in Linux?

You can use the killall command as follows:

killall node

javascript set cookie with expire time

Use like this (source):

function setCookie(c_name,value,exdays)
{

var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie = c_name+"="+c_value+"; path=/";
}

Get list of JSON objects with Spring RestTemplate

Maybe this way...

ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(urlGETList, Object[].class);
Object[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();

Controller code for the RequestMapping

@RequestMapping(value="/Object/getList/", method=RequestMethod.GET)
public @ResponseBody List<Object> findAllObjects() {

    List<Object> objects = new ArrayList<Object>();
    return objects;
}

ResponseEntity is an extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods. In RestTemplate this class is returned by getForEntity() and exchange().

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

HTML embed autoplay="false", but still plays automatically

Just set using JS as follows:

<script>
    var vid = document.getElementById("myVideo");
    vid.autoplay = false;
    vid.load();
</script>

Set true to turn on autoplay. Set false to turn off autoplay.

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay

Get current controller in view

You can use any of the below code to get the controller name

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

If you are using MVC 3 you can use

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

What is the behavior difference between return-path, reply-to and from?

Another way to think about Return-Path vs Reply-To is to compare it to snail mail.

When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path.

Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To.

In essence, a Postage Return Address is comparable to SMTP's Return-Path header and SMTP's Reply-To header is similar to the replying instructions contained in a letter.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

iPhone Safari Web App opens links in new window

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        e.preventDefault();
        window.location = $(this).attr('href');
    }
});

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

Visual Studio popup: "the operation could not be completed"

I removed an old project from the solution, after that the error occurred. I had to open the .sln file in notepad and delete the .dll reference tot he old project that I removed. After that it worked.

Catch Ctrl-C in C

Set up a trap (you can trap several signals with one handler):

signal (SIGQUIT, my_handler);
signal (SIGINT, my_handler);

Handle the signal however you want, but be aware of limitations and gotchas:

void my_handler (int sig)
{
  /* Your code here. */
}

How to target only IE (any version) within a stylesheet?

After experiencing issues with sites breaking on Edge when using High Contrast Mode, I came across the following work by Jeff Clayton:

https://browserstrangeness.github.io/css_hacks.html

It's a crazy, weird media query, but those are easier to use in Sass:

@media screen and (min-width:0\0) and (min-resolution:+72dpi), \0screen\,screen\9 {
   .selector { rule: value };
}

This targets IE versions expect for IE8.

Or you can use:

@media screen\0 {
  .selector { rule: value };
}

Which targets IE8-11, but also triggers FireFox 1.x (which for my use case, doesn't matter).

Right now I'm testing with print support, and this seems to be working okay:

@media all\0 {
  .selector { rule: value };
}

Setting Windows PATH for Postgres tools

I am using Windows 8 and the above solutions did not work out for me. I downgraded Postgres from 9.4 to 9.3. Man,it worked :)

Android getResources().getDrawable() deprecated API 22

Edit: see my blog post on the subject for a more complete explanation


You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.***)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

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

JAXB is simple to use and is included in Java 6 SE. With JAXB, or other XML data binding such as Simple, you don't have to handle the XML yourself, most of the work is done by the library. The basic usage is to add annotation to your existing POJO. These annotation are then used to generate an XML Schema for you data and also when reading/writing your data from/to a file.

delete vs delete[] operators in C++

This the basic usage of allocate/DE-allocate pattern in c++ malloc/free, new/delete, new[]/delete[]

We need to use them correspondingly. But I would like to add this particular understanding for the difference between delete and delete[]

1) delete is used to de-allocate memory allocated for single object

2) delete[] is used to de-allocate memory allocated for array of objects

class ABC{}

ABC *ptr = new ABC[100]

when we say new ABC[100], compiler can get the information about how many objects that needs to be allocated(here it is 100) and will call the constructor for each of the objects created

but correspondingly if we simply use delete ptr for this case, compiler will not know how many objects that ptr is pointing to and will end up calling of destructor and deleting memory for only 1 object(leaving the invocation of destructors and deallocation of remaining 99 objects). Hence there will be a memory leak.

so we need to use delete [] ptr in this case.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

Actually I had wrongly put href="", and hence the html file was referencing itself as the CSS. Mozilla had the similar bug once, and I got the answer from there.

Escape string Python for MySQL

conn.escape_string()

See MySQL C API function mapping: http://mysql-python.sourceforge.net/MySQLdb.html

Play/pause HTML 5 video using JQuery

Your solution shows the issue here -- play is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element. You give an example of how to do this with the native DOM functions. The jQuery equivalent -- if you wanted to do this to fit in with an existing jQuery selection -- would be $('#videoId').get(0).play(). (get gets the native DOM element from the jQuery selection.)

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

How to skip the OPTIONS preflight request?

I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.

express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

How can I turn a DataTable to a CSV?

Read this and this?


A better implementation would be

var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
    result.Append(table.Columns[i].ColumnName);
    result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}

foreach (DataRow row in table.Rows)
{
    for (int i = 0; i < table.Columns.Count; i++)
    {
        result.Append(row[i].ToString());
        result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
    }
}
 File.WriteAllText("test.csv", result.ToString());

Side-by-side list items as icons within a div (css)

I used a combination of the above to achieve a working result; Change float to Left and display Block the li itself HTML:

<ol class="foo">
    <li>bar1</li>
    <li>bar2</li>
</ol>

CSS:

.foo li {
    display: block;
    float: left;
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin: 2px;
}

Why does JavaScript only work after opening developer tools in IE once?

Besides the 'console' usage issue mentioned in accepted answer and others,there is at least another reason why sometimes pages in Internet Explorer work only with the developer tools activated.

When Developer Tools is enabled, IE doesn't really uses its HTTP cache (at least by default in IE 11) like it does in normal mode.

It means if your site or page has a caching problem (if it caches more than it should for example - that was my case), you will not see that problem in F12 mode. So if the javascript does some cached AJAX requests, they may not work as expected in normal mode, and work fine in F12 mode.

How to automatically close cmd window after batch file execution?

If you want to separate the commands into one command per file, you can do

cmd /c start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1"

and in the other file, you can do

cmd /c start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow

The command cmd /c will close the command-prompt window after the exe was run.

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

error_reporting(E_ALL) does not produce error

Your file has syntax error, so your file was not interpreted, so settings was not changed and you have blank page.

You can separate your file to two.

index.php

<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';

error.php

<?
echo('catch this -> ' ;. $thisdoesnotexist);

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

If you are on a Mac, press command shift G and in the box type /users and then go, next click on your user name and navigate to netbeansprojects and open it. Then delete the ones in there that are causing problems. You can then create your project.

Note: I had moved my wordpress folder to my desktop trying to figure this out, so I dropped it back into the origional location and it works fine. So if you did this, just replace the wordpress folder after deleting the problem projects from the netbeansprojects folder and its contents back to the original installation folder.

Hope this helps...:)

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

Why does background-color have no effect on this DIV?

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.

Why should text files end with a newline?

A separate use case: when your text file is version controlled (in this case specifically under git although it applies to others too). If content is added to the end of the file, then the line that was previously the last line will have been edited to include a newline character. This means that blameing the file to find out when that line was last edited will show the text addition, not the commit before that you actually wanted to see.

How to use XMLReader in PHP?

It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

ie8 var w= window.open() - "Message: Invalid argument."

For me the issue was with a dash "-" in the window name field. I removed the dashes and IE does not error out and in fact opens the window.

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

I used Adobe's detection kit, originally suggested by justpassinby. Their system is nice because it detects the version number and compares it for you against your 'required version'

One bad thing is it does an alert showing the detected version of flash, which isn't very user friendly. All of a sudden a box pops up with some seemingly random numbers.

Some modifications you might want to consider:

  • remove the alert
  • change it so it returns an object (or array) --- first element is boolean true/false for "was the required version found on user's machine" --- second element is the actual version number found on user's machine

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

A workaround for CONTAINS: If you don't want to create a full text Index on the column, and performance is not one of your priorities you could use the LIKE statement which doesn't need any prior configuration:

Example: find all Products that contains the letter Q:

SELECT ID, ProductName
FROM [ProductsDB].[dbo].[Products]
WHERE [ProductsDB].[dbo].[Products].ProductName LIKE '%Q%'

How to count the number of files in a directory using Python

If you'll be using the standard shell of the operating system, you can get the result much faster rather than using pure pythonic way.

Example for Windows:

import os
import subprocess

def get_num_files(path):
    cmd = 'DIR \"%s\" /A-D /B /S | FIND /C /V ""' % path
    return int(subprocess.check_output(cmd, shell=True))

Skipping every other element after the first

# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
    # Does this element belong in the resulting list?
    if i%2==0:
        # Add this element to the resulting list
        new_list.append(elements[i])
    # Increment i
    i +=2

return new_list

How to catch a click event on a button?

/src/com/example/MyClass.java

package com.example

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MyClass extends Activity
{

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

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
         ImageView iv = (ImageView) findViewById(R.id.imageview1);
         iv.setVisibility(View.VISIBLE);
      }
    });

  }
}

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <Button 
      android:text="Button"
      android:id="@+id/button1"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
    />
    <ImageView 
      android:src="@drawable/image" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:id="@+id/imageview1"
      android:visibility="invisible"
    />
</LinearLayout>

Do fragments really need an empty constructor?

Yes they do.

You shouldn't really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

For example:

public static final MyFragment newInstance(int title, String message) {
    MyFragment f = new MyFragment();
    Bundle bdl = new Bundle(2);
    bdl.putInt(EXTRA_TITLE, title);
    bdl.putString(EXTRA_MESSAGE, message);
    f.setArguments(bdl);
    return f;
}

And of course grabbing the args this way:

@Override
public void onCreate(Bundle savedInstanceState) {
    title = getArguments().getInt(EXTRA_TITLE);
    message = getArguments().getString(EXTRA_MESSAGE);

    //...
    //etc
    //...
}

Then you would instantiate from your fragment manager like so:

@Override
public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null){
        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content, MyFragment.newInstance(
                R.string.alert_title,
                "Oh no, an error occurred!")
            )
            .commit();
    }
}

This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.

Reason - Extra reading

I thought I would explain why for people wondering why.

If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java

You will see the instantiate(..) method in the Fragment class calls the newInstance method:

public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
    try {
        Class<?> clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException("Trying to instantiate a class " + fname
                        + " that is not a Fragment", new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.getConstructor().newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.setArguments(args);
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (NoSuchMethodException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": could not find Fragment constructor", e);
    } catch (InvocationTargetException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": calling Fragment constructor caused an exception", e);
    }
}

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public and that that class loader allows access to it.

It's a pretty nasty method all in all, but it allows the FragmentManger to kill and recreate Fragments with states. (The Android subsystem does similar things with Activities).

Example Class

I get asked a lot about calling newInstance. Do not confuse this with the class method. This whole class example should show the usage.

/**
 * Created by chris on 21/11/2013
 */
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {

    public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
        StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();

        final Bundle args = new Bundle(1);
        args.putString(EXTRA_CRS_CODE, crsCode);
        fragment.setArguments(args);

        return fragment;
    }

    // Views
    LinearLayout mLinearLayout;

    /**
     * Layout Inflater
     */
    private LayoutInflater mInflater;
    /**
     * Station Crs Code
     */
    private String mCrsCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;
        return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
        //Do stuff
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
    }

    // Other methods etc...
}

laravel Unable to prepare route ... for serialization. Uses Closure

The Actual solution of this problem is changing first line in web.php

Just replace Welcome route with following route

Route::view('/', 'welcome');

If still getting same error than you probab

How can I define an interface for an array of objects with Typescript?

Use like this!

interface Iinput {
  label: string
  placeholder: string
  register: any
  type?: string
  required: boolean
}


// This is how it can be done

const inputs: Array<Iinput> = [
  {
    label: "Title",
    placeholder: "Bought something",
    register: register,
    required: true,
  },
]

How to run .sql file in Oracle SQL developer tool to import database?

As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:

  • Click and drag your .sql file over to Oracle SQL Developer
  • The contents will appear in a "SQL Worksheet"
  • Click "Run Script" button, or hit F5, to run

enter image description here

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

Convert wchar_t to char

In general, no. int(wchar_t(255)) == int(char(255)) of course, but that just means they have the same int value. They may not represent the same characters.

You would see such a discrepancy in the majority of Windows PCs, even. For instance, on Windows Code page 1250, char(0xFF) is the same character as wchar_t(0x02D9) (dot above), not wchar_t(0x00FF) (small y with diaeresis).

Note that it does not even hold for the ASCII range, as C++ doesn't even require ASCII. On IBM systems in particular you may see that 'A' != 65

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Just default the variable to the expected type:

(number=1) => ...
(number=1.0) => ...
(string='str') ...

How to get substring in C

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "SexDrugsRocknroll";
    char dest[5] = { 0 }; // 4 chars + terminator */
    int len = strlen(src);
    int i = 0;

    while (i*4 < len) {
        strncpy(dest, src+(i*4), 4);
        i++;

        printf("loop %d : %s\n", i, dest);
    }
}

How would I get a cron job to run every 30 minutes?

crontab does not understand "intervals", it only understands "schedule"

valid hours: 0-23 -- valid minutes: 0-59

example #1

30 * * * * your_command

this means "run when the minute of each hour is 30" (would run at: 1:30, 2:30, 3:30, etc)

example #2

*/30 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

example #3

0,30 * * * * your_command

this means "run when the minute of each hour is 0 or 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

it's another way to accomplish the same results as example #2

example #4

19 * * * * your_command

this means "run when the minute of each hour is 19" (would run at: 1:19, 2:19, 3:19, etc)

example #5

*/19 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 19" (would run at: 1:19, 1:38, 1:57, 2:19, 2:38, 2:57 etc)

note: several refinements have been made to this post by various users including the author

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>

script:

<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
                    margins.top, {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
                    },
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

How do I get the current username in .NET using C#?

You may also want to try using:

Environment.UserName;

Like this...:

string j = "Your WindowsXP Account Name is: " + Environment.UserName;

Hope this has been helpful.

How to append data to div using JavaScript?

you can use jQuery. which make it very simple.

just download the jQuery file add jQuery into your HTML
or you can user online link:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

and try this:

 $("#divID").append(data);

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.

def getHeight(self,root, method='links'):
    c_node = root
    cur_lvl_nodes = [root]
    nxt_lvl_nodes = []
    height = {'links': -1, 'nodes': 0}[method]

    while(cur_lvl_nodes or nxt_lvl_nodes):
        for c_node in cur_lvl_nodes:
            for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
                nxt_lvl_nodes.append(n_node)

        cur_lvl_nodes = nxt_lvl_nodes
        nxt_lvl_nodes = []
        height += 1

    return height

Hide Command Window of .BAT file that Executes Another .EXE File

I used this to start a cmd file from C#:

Process proc = new Process();
proc.StartInfo.WorkingDirectory = "myWorkingDirectory";
proc.StartInfo.FileName = "myFileName.cmd";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For VS2015 and VS2017

Works with TFS (on-prem) or VSO (Visual Studio Online - the Azure-hosted offering)

The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.

I recommend you follow NuGet's instructions but just to recap what I did:

  1. Make sure your packages folder is not committed to TFS. If it is, get it out of there.
  2. Everything else we create below goes into the same folder that your .sln file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this).
  3. Create a .nuget folder. You can use Windows Explorer to name it .nuget. for it to successfully save as .nuget (it automatically removes the last period) but directly trying to name it .nuget may not work (you may get an error or it may change the name, depending on your version of Windows). Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nuget
  4. Inside of that folder, create a NuGet.config file and add the following contents and save it:

NuGet.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <solution>
        <add key="disableSourceControlIntegration" value="true" />
    </solution>
</configuration>
  1. Go back in your .sln's folder and create a new text file and name it .tfignore (if using Windows Explorer, use the same trick as above and name it .tfignore.)
  2. Put the following content into that file:

.tfignore:

# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's 
# not in the same folder as .tfignore.
packages

# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
  1. Save all of this, commit it to TFS, then close & re-open Visual Studio and the Team Explorer should no longer identify the packages folder as a pending check-in.
  2. Copy/pasted via Windows Explorer the .tfignore file and .nuget folder to all of my various solutions and committed them and I no longer have the packages folder trying to sneak into my source control repo!

Further Customization

While not mine, I have found this .tfignore template by sirkirby to be handy. The example in my answer covers the Nuget packages folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

From what i have observed there might be two reasons for this Exception to occur: (1)Your Driver name is not spelled Correctly. (2)Driver hasn't been Associated Properly with the Java Project Steps to follow in Eclipse: (1)Create a new Java Project. (2)copy The connector Jar file (3)Right Click on the Java project and paste it there. (4)Right click on the Java project -> Properties ->Java Build Path - >libraries-> Add Jar ->choose ur project(select the jar file from dropdown) and click ok.

Difference between Spring MVC and Struts MVC

Spring MVC is deeply integreated in Spring, Struts MVC is not.

Show hide divs on click in HTML and CSS without jQuery

Of course! jQuery is just a library that utilizes javascript after all.

You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.

elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';

Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.

ComboBox SelectedItem vs SelectedValue

I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.

Here is a reference to the focus events that occur on controls:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

Border color on default input style

If I understand your question correctly this should solve it:

http://jsfiddle.net/wvk2mnsf/

HTML - create a simple input field.

<input type="text" id="giraffe" />

CSS - clear out the native outline so you can set your own and it doesn't look weird with a bluey red outline.

input:focus {
    outline: none;
}
.error-input-border {
    border: 1px solid #FF0000;
}

JS - on typing in the field set red border class declared in the CSS

document.getElementById('giraffe').oninput = function() { this.classList.add('error-input-border'); }

This has a lot of information on the latest standards too: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

How to add a vertical Separator?

<Style x:Key="MySeparatorStyle" TargetType="{x:Type Separator}">
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/>
                <Setter Property="Margin" Value="10,0,10,0"/>
                <Setter Property="Focusable" Value="false"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Separator}">
                            <Border 
                                  BorderBrush="{TemplateBinding BorderBrush}" 
                                  BorderThickness="{TemplateBinding BorderThickness}" 
                                  Background="{TemplateBinding Background}" 
                                  Height="20" 
                                  Width="3" 
                                  SnapsToDevicePixels="true"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

use

<StackPanel  Orientation="Horizontal"  >
       <TextBlock>name</TextBlock>
           <Separator Style="{StaticResource MySeparatorStyle}" ></Separator>
       <Button>preview</Button>
 </StackPanel>

Python list directory, subdirectory, and files

Couldn't comment so writing answer here. This is the clearest one-line I have seen:

import os
[os.path.join(path, name) for path, subdirs, files in os.walk(root) for name in files]

type object 'datetime.datetime' has no attribute 'datetime'

For python 3.3

from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)

What is the difference between a HashMap and a TreeMap?

You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.

Disable all Database related auto configuration in Spring Boot

Also if you use Spring Actuator org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration might be initializing DataSource as well.

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

Use of *args and **kwargs

One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:

def mydecorator( f ):
   @functools.wraps( f )
   def wrapper( *args, **kwargs ):
      print "Calling f", args, kwargs
      v = f( *args, **kwargs )
      print "f returned", v
      return v
   return wrapper

How to simplify a null-safe compareTo() implementation?

Another Apache ObjectUtils example. Able to sort other types of objects.

@Override
public int compare(Object o1, Object o2) {
    String s1 = ObjectUtils.toString(o1);
    String s2 = ObjectUtils.toString(o2);
    return s1.toLowerCase().compareTo(s2.toLowerCase());
}

Bootstrap 3 navbar active li not changing background-color

You need to add CSS to .active instead of .active a.

Fiddle: http://jsfiddle.net/T5X6h/2/

Something like this:

.navbar-default .navbar-nav > .active{
    color: #000;
    background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #000;
    background: #d65c14;
}

How do you check if a variable is an array in JavaScript?

If you are using Angular, you can use the angular.isArray() function

var myArray = [];
angular.isArray(myArray); // returns true

var myObj = {};
angular.isArray(myObj); //returns false

http://docs.angularjs.org/api/ng/function/angular.isArray

What is the connection string for localdb for version 11

I had the same problem for a bit. I noticed that I had:

Data Source= (localdb)\v11.0"

Simply by adding one back-slash it solved the problem for me:

Data Source= (localdb)\\v11.0"

How to set an image as a background for Frame in Swing GUI of java?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
  JButton b1;
  JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
 One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);

// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads  \\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
  setSize(399,399);
   setSize(400,400);
   }
   public static void main(String args[])
  {
   new BackgroundImageJFrame();
 }
 }

Java SSLHandshakeException "no cipher suites in common"

This problem can be caused by undue manipulation of the enabled cipher suites at the client or the server, but I suspect the most common cause is the server not having a private key and certificate at all.

NB:

ssl.setEnabledCipherSuites(sc.getServerSocketFactory().getSupportedCipherSuites());

Get rid of this line. Your server is insecure enough already with that insecure TrustManager. Then run your server with -Djavax.net.debug=SSL,handshake, try one connect, and post the resulting output here.

Using Exit button to close a winform program

If you only want to Close the form than you can use this.Close(); else if you want the whole application to be closed use Application.Exit();

How to convert a byte to its binary string representation

Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

In most cases getting rid of infinite and null values solve this problem.

get rid of infinite values.

df.replace([np.inf, -np.inf], np.nan, inplace=True)

get rid of null values the way you like, specific value such as 999, mean, or create your own function to impute missing values

df.fillna(999, inplace=True)

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

Failed to Connect to MySQL at localhost:3306 with user root

It worked for me this way:

Step1: Open System Preference > MySQL > Initialize Database.

Step2: Put password you used while installing MySQL.

Step3: Start MySQL server.

Step4: Come back to MySQL Workbench and double connect/ create a new one.

PHP - remove <img> tag from string

You need to assign the result back to $content as preg_replace does not modify the original string.

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

Creating a range of dates in Python

From above answers i created this example for date generator

import datetime
date = datetime.datetime.now()
time = date.time()
def date_generator(date, delta):
  counter =0
  date = date - datetime.timedelta(days=delta)
  while counter <= delta:
    yield date
    date = date + datetime.timedelta(days=1)
    counter +=1

for date in date_generator(date, 30):
   if date.date() != datetime.datetime.now().date():
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, datetime.time.max)
   else:
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, time)
   print('start_date---->',start_date,'end_date---->',end_date)

In java how to get substring from a string till a character c?

look at String.indexOf and String.substring.

Make sure you check for -1 for indexOf.

Linux bash: Multiple variable assignment

I think this might help...

In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:

DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

what innerHTML is doing in javascript?

It represents the textual contents of a given HTML tag. Can also contain tags of its own.

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

How to reverse a singly linked list using only two pointers?

As an alternative, you can use recursion-

struct node* reverseList(struct node *head)
{
    if(head == NULL) return NULL;
    if(head->next == NULL) return head;

    struct node* second = head->next;       
    head->next = NULL;

    struct node* remaining = reverseList(second);
    second->next = head;

    return remaining;
}

How to make a promise from setTimeout

Update (2017)

Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise constructor (the Promise executor) which receives the functions for resolving/rejecting the promise as arguments.

First, since async now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later as the name of the function to avoid confusion.

Basic Delay

Using native promises (or a faithful polyfill) it would look like this:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

Note that that assumes a version of setTimeout that's compliant with the definition for browsers where setTimeout doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).

Basic Delay with Value

If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

If you're using ES2015+ arrow functions, that can be more concise:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

or even

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

Cancellable Delay with Value

If you want to make it possible to cancel the timeout, you can't just return a promise from later, because promises can't be cancelled.

But we can easily return an object with a cancel method and an accessor for the promise, and reject the promise on cancel:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

Live Example:

_x000D_
_x000D_
const later = (delay, value) => {_x000D_
    let timer = 0;_x000D_
    let reject = null;_x000D_
    const promise = new Promise((resolve, _reject) => {_x000D_
        reject = _reject;_x000D_
        timer = setTimeout(resolve, delay, value);_x000D_
    });_x000D_
    return {_x000D_
        get promise() { return promise; },_x000D_
        cancel() {_x000D_
            if (timer) {_x000D_
                clearTimeout(timer);_x000D_
                timer = 0;_x000D_
                reject();_x000D_
                reject = null;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
  l2.cancel();_x000D_
}, 150);
_x000D_
_x000D_
_x000D_


Original Answer from 2014

Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.

Then later would tend to look something like this:

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

In a comment on the question, I asked:

Are you trying to create your own promise library?

and you said

I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it

To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

Deny direct access to all .php files except index.php

You can try defining a constant in index.php and add something like

if (!defined("YOUR_CONSTANT")) die('No direct access');

to the beginning of the other files.

OR, you can use mod_rewrite and redirect requests to index.php, editing .htaccess like this:

RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /index.php/$1 [L,R=301]

Then you should be able to analyze all incoming requests in the index.php and take according actions.

If you want to leave out all *.jpg, *.gif, *.css and *.png files, for example, then you should edit second line like this:

RewriteCond $1 !^(index\.php|*\.jpg|*\.gif|*\.css|*\.png)

Passing an Array as Arguments, not an Array, in PHP

As has been mentioned, as of PHP 5.6+ you can (should!) use the ... token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:

<?php
function variadic($arg1, $arg2)
{
    // Do stuff
    echo $arg1.' '.$arg2;
}

$array = ['Hello', 'World'];

// 'Splat' the $array in the function call
variadic(...$array);

// 'Hello World'

Note: array items are mapped to arguments by their position in the array, not their keys.

As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array.

Aside

Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.

(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)

This is great for making sure an array contains items of a specific type:

<?php

// Define the function...

function variadic($var, SomeClass ...$items)
{
    // $items will be an array of objects of type `SomeClass`
}

// Then you can call...

variadic('Hello', new SomeClass, new SomeClass);

// or even splat both ways

$items = [
    new SomeClass,
    new SomeClass,
];

variadic('Hello', ...$items);

How to update std::map after using the find method?

If you already know the key, you can directly update the value at that key using m[key] = new_value

Here is a sample code that might help:

map<int, int> m;

for(int i=0; i<5; i++)
    m[i] = i;

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
//Output: 0 1 2 3 4

m[4] = 7;  //updating value at key 4 here

cout<<"\n"; //Change line

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
// Output: 0 1 2 3 7    

How to scroll to bottom in a ScrollView on activity startup

It needs to be done as following:

    getScrollView().post(new Runnable() {

        @Override
        public void run() {
            getScrollView().fullScroll(ScrollView.FOCUS_DOWN);
        }
    });

This way the view is first updated and then scrolls to the "new" bottom.

check if a file is open in Python

if myfile.closed == False:
   print("File is still open ################")

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

How to select all rows which have same value in some column

select *
from Table1 as t1
where
    exists (
        select *
        from Table1 as t2 
        where t2.Phone = t1.Phone and t2.id <> t1.id
    )

sql fiddle demo

System.out.println() shortcut on Intellij IDEA

In Idea 17eap:

sout: Prints

System.out.println();

soutm: Prints current class and method names to System.out

System.out.println("$CLASS_NAME$.$METHOD_NAME$");

soutp: Prints method parameter names and values to System.out

System.out.println($FORMAT$);

soutv: Prints a value to System.out

System.out.println("$EXPR_COPY$ = " + $EXPR$);

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

How can I convert radians to degrees with Python?

-fix- because you want to change from radians to degrees, it is actually rad=deg * math.pi /180 and not deg*180/math.pi

import math
x=1                # in deg
x = x*math.pi/180  # convert to rad
y = math.cos(x)    # calculate in rad

print y

in 1 line it can be like this

y=math.cos(1*math.pi/180)

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later

SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]

Ruby on Rails: How do I add placeholder text to a f.text_field?

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

Determine if a String is an Integer in Java

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}

Proper indentation for Python multiline strings

It depends on how you want the text to display. If you want it all to be left-aligned then either format it as in the first snippet or iterate through the lines left-trimming all the space.

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

How can the error 'Client found response content type of 'text/html'.. be interpreted

The problem I had was related to SOAP version. The asmx service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.

To fix that, is necessary add:

using (wsWebService yourService = new wsWebService())
{
    yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
    yourService.UseDefaultCredentials = true; // this line depends on your authentication type
    yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
    var result = yourService.SomeMethod("Parameter");
}

Where wsWebService is the name of the class generated as a reference.

What is makeinfo, and how do I get it?

If it doesn't show up in your package manager (i.e. apt-cache search texinfo) and even apt-file search bin/makeinfo is no help, you may have to enable non-free/restricted packages for your package manager.

For ubuntu, sudo $EDITOR /etc/apt/sources.list and add restricted.

deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main

For debian, sudo $EDITOR /etc/apt/sources.list and add non-free. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.

After a sudo apt-get udpate you should find the required package.

Cross domain POST request is not sending cookie Ajax Jquery

There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

To have a cookie sent by the browser to another site during a request the following criteria must be met:

A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

How to Install pip for python 3.7 on Ubuntu 18?

I installed pip3 using

python3.7 -m pip install pip

But upon using pip3 to install other dependencies, it was using python3.6.
You can check the by typing pip3 --version

Hence, I used pip3 like this (stated in one of the above answers):

python3.7 -m pip install <module>

or use it like this:

python3.7 -m pip install -r requirements.txt

I made a bash alias for later use in ~/.bashrc file as alias pip3='python3.7 -m pip'. If you use alias, don't forget to source ~/.bashrc after making the changes and saving it.

notifyDataSetChange not working from custom adapter

Add this code

runOnUiThread(new Runnable() { public void run() {
               adapter = new CustomAdapter(anotherdata);
            adapter.notifyDataSetChanged();
            }
        });

How to create an array containing 1...N

There is small function, it allow to use construction like [1, 2].range(3, 4) -> [1, 2, 3, 4] also it works with negative params. Enjoy.

Array.prototype.range = function(from, to)
{
   var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
   var tmp = Array.apply(this, {"length": range}).map(function()
      {
         return (increase)?from++ : from--;
      }, Number);

   return this.concat(tmp);
};

How should I multiple insert multiple records?

Following up @Tim Mahy - There's two possible ways to feed SqlBulkCopy: a DataReader or via DataTable. Here the code for DataTable:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
foreach (Entry entry in entries)
    dt.Rows.Add(new string[] { entry.Id, entry.Name });

using (SqlBulkCopy bc = new SqlBulkCopy(connection))
{   // the following 3 lines might not be neccessary
    bc.DestinationTableName = "Entries";
    bc.ColumnMappings.Add("Id", "Id");
    bc.ColumnMappings.Add("Name", "Name");

    bc.WriteToServer(dt);
}

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

Python SQLite: database is locked

I'm presuming you are actually using sqlite3 even though your code says otherwise. Here are some things to check:

  1. That you don't have a hung process sitting on the file (unix: $ fuser cache.db should say nothing)
  2. There isn't a cache.db-journal file in the directory with cache.db; this would indicate a crashed session that hasn't been cleaned up properly.
  3. Ask the database shell to check itself: $ sqlite3 cache.db "pragma integrity_check;"
  4. Backup the database $ sqlite3 cache.db ".backup cache.db.bak"
  5. Remove cache.db as you probably have nothing in it (if you are just learning) and try your code again
  6. See if the backup works $ sqlite3 cache.db.bak ".schema"

Failing that, read Things That Can Go Wrong and How to Corrupt Your Database Files

Change the spacing of tick marks on the axis of a plot?

And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:

plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))

AWK: Access captured group from line pattern

With gawk, you can use the match function to capture parenthesized groups.

gawk 'match($0, pattern, ary) {print ary[1]}' 

example:

echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}' 

outputs cd.

Note the specific use of gawk which implements the feature in question.

For a portable alternative you can achieve similar results with match() and substr.

example:

echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'

outputs cd.

Regular Expression Match to test for a valid year

The "accepted" answer to this question is both incorrect and myopic.

It is incorrect in that it will match strings like 0001, which is not a valid year.

It is myopic in that it will not match any values above 9999. Have we already forgotten the lessons of Y2K? Instead, use the regular expression:

^[1-9]\d{3,}$

If you need to match years in the past, in addition to years in the future, you could use this regular expression to match any positive integer:

^[1-9]\d*$

Even if you don't expect dates from the past, you may want to use this regular expression anyway, just in case someone invents a time machine and wants to take your software back with them.

Note: This regular expression will match all years, including those before the year 1, since they are typically represented with a BC designation instead of a negative integer. Of course, this convention could change over the next few millennia, so your best option is to match any integer—positive or negative—with the following regular expression:

^-?[1-9]\d*$

implements Closeable or implements AutoCloseable

Recently I have read a Java SE 8 Programmer Guide ii Book.

I found something about the difference between AutoCloseable vs Closeable.

The AutoCloseable interface was introduced in Java 7. Before that, another interface existed called Closeable. It was similar to what the language designers wanted, with the following exceptions:

  • Closeable restricts the type of exception thrown to IOException.
  • Closeable requires implementations to be idempotent.

The language designers emphasize backward compatibility. Since changing the existing interface was undesirable, they made a new one called AutoCloseable. This new interface is less strict than Closeable. Since Closeable meets the requirements for AutoCloseable, it started implementing AutoCloseable when the latter was introduced.

Calculating the angle between the line defined by two points

"the origin is at the top-left of the screen and the Y-Coordinate increases going down, while the X-Coordinate increases to the right like normal. I guess my question becomes, do I have to convert the screen coordinates to Cartesian coordinates before applying the above formula?"

If you were calculating the angle using Cartesian coordinates, and both points were in quadrant 1 (where x>0 and y>0), the situation would be identical to screen pixel coordinates (except for the upside-down-Y thing. If you negate Y to get it right-side up, it becomes quadrant 4...). Converting screen pixel coordinates to Cartesian doesnt really change the angle.

How do I create a self-signed certificate for code signing on Windows?

As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.

  1. Generate the key:
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
  1. Export the certificate without the private key:
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt

The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).

  1. Import it as Trusted Publisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
  1. Import it as a Root certificate authority.
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
  1. Sign the script (assuming here it's named script.ps1, fix the path accordingly).
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)

Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.

Print Pdf in C#

It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.

Here is the code for the approach I worked out on a win form web browser control:

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"path\to\file");
    }  

    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {   
        //Progress Changed fires multiple times, however after the Navigated event it is fired only once,
        //and at this point it is ready to print
        webBrowser1.ProgressChanged += (o, args) => 
        {
            webBrowser1.Print();//Note this does not print only brings up the print preview dialog
            //Should be on a separate task to ensure the main thread 
            //can fully initialize the print dialog 
            Task.Factory.StartNew(() => 
            {
                Thread.Sleep(1000);//We need to wait before we can send enter
                //This assumes that the print preview is still in focus
                Action g = () =>
                {
                    SendKeys.SendWait("{ENTER}");
                };
                this.Invoke(g);
            });
        };
    }

java.io.IOException: Server returned HTTP response code: 500

HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode() and in case of errors, read the HttpURLConnection#getErrorStream() instead. It may namely contain information about the problem.

If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.

See also:

Reading file contents on the client-side in javascript in various browsers

Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX

var CallBackFunction = function(content) {
  alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
  try {
    var file = FileElement.files[0];
    var contents_ = "";

    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function(evt) {
        CallBackFunction(evt.target.result);
      }
      reader.onerror = function(evt) {
        alert("Error reading file");
      }
    }
  } catch (Exception) {
    var fall_back = ieReadFile(FileElement.value);
    if (fall_back != false) {
      CallBackFunction(fall_back);
    }
  }
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
  try {
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile(filename, 1);
    var contents = fh.ReadAll();
    fh.Close();
    return contents;
  } catch (Exception) {
    alert(Exception);
    return false;
  }
}

How to change the timeout on a .NET WebClient object

You need to use HttpWebRequest rather than WebClient as you can't set the timeout on WebClient without extending it (even though it uses the HttpWebRequest). Using the HttpWebRequest instead will allow you to set the timeout.

if statement checks for null but still throws a NullPointerException

Change Below line

if (str == null | str.length() == 0) {

into

if (str == null || str.isEmpty()) {

now your code will run corectlly. Make sure str.isEmpty() comes after str == null because calling isEmpty() on null will cause NullPointerException. Because of Java uses Short-circuit evaluation when str == null is true it will not evaluate str.isEmpty()

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Get int from String, also containing letters, in Java

Just go through the string, building up an int as usual, but ignore non-number characters:

int res = 0;
for (int i=0; i < str.length(); i++) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') continue;
    res = res * 10 + (c - '0');
}

How to pass boolean values to a PowerShell script from a command prompt

In PowerShell, boolean parameters can be declared by mentioning their type before their variable.

    function GetWeb() {
             param([bool] $includeTags)
    ........
    ........
    }

You can assign value by passing $true | $false

    GetWeb -includeTags $true

Git commit with no commit message

And if you add an alias for it then it's even better right?

git config --global alias.nccommit 'commit -a --allow-empty-message -m ""'

Now you just do an nccommit, nc because of no comment, and everything should be commited.

setting an environment variable in virtualenv

You could try:

export ENVVAR=value

in virtualenv_root/bin/activate. Basically the activate script is what is executed when you start using the virtualenv so you can put all your customization in there.

Why can't I declare static methods in an interface?

I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:

Math.add(2, 3);

If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.

C# Passing Function as Argument

public static T Runner<T>(Func<T> funcToRun)
{
    //Do stuff before running function as normal
    return funcToRun();
}

Usage:

var ReturnValue = Runner(() => GetUser(99));

C++ Structure Initialization

It's not implemented in C++. (also, char* strings? I hope not).

Usually if you have so many parameters it is a fairly serious code smell. But instead, why not simply value-initialize the struct and then assign each member?

Clone an image in cv2 python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Is java.sql.Timestamp timezone specific?

It is specific from your driver. You need to supply a parameter in your Java program to tell it the time zone you want to use.

java -Duser.timezone="America/New_York" GetCurrentDateTimeZone

Further this:

to_char(new_time(sched_start_time, 'CURRENT_TIMEZONE', 'NEW_TIMEZONE'), 'MM/DD/YY HH:MI AM')

May also be of value in handling the conversion properly. Taken from here

Setting the Textbox read only property to true using JavaScript

it depends on how you trigger the event. the key you are looking is textbox.clientid.

x.aspx code

<script type="text/javascript">

   function disable_textbox(tid) {
        var mytextbox = document.getElementById(tid);
         mytextbox.disabled=false
   }
</script>

code behind x.aspx.cs

    string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID  ");</script>";
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);

Filling a List with all enum values in Java

This is a bit more readable:

Object[] allValues = all.getDeclaringClass().getEnumConstants();

How to set upload_max_filesize in .htaccess?

Both commands are correct

php_value post_max_size 30M 
php_value upload_max_filesize 30M 

BUT to use the .htaccess you have to enable rewrite_module in Apache config file. In httpd.conf find this line:

# LoadModule rewrite_module modules/mod_rewrite.so

and remove the #.

Best lightweight web server (only static content) for Windows

The smallest one I know is lighttpd.

Security, speed, compliance, and flexibility -- all of these describe lighttpd (pron. lighty) which is rapidly redefining efficiency of a webserver; as it is designed and optimized for high performance environments. With a small memory footprint compared to other web-servers, effective management of the cpu-load, and advanced feature set (FastCGI, SCGI, Auth, Output-Compression, URL-Rewriting and many more) lighttpd is the perfect solution for every server that is suffering load problems. And best of all it's Open Source licensed under the revised BSD license.

Edit: removed Windows version link, now a spam/malware plugin site.

Click outside menu to close in jquery

what about this?

    $(this).mouseleave(function(){  
        var thisUI = $(this);
        $('html').click(function(){
                thisUI.hide();
            $('html').unbind('click');
         });
     });

Maven Modules + Building a Single Specific Module

If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

You can define a multi-module project with an aggregator pom to build a set of projects.

It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

"Permission Denied" trying to run Python on Windows 10

For me, I tried manage app execution aliases and got an error that python3 is not a command so for that, I used py instead of python3 and it worked

I don't know why this is happening but It worked for me

PHP checkbox set to check based on database value

Add this code inside your input tag

<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>

How to copy commits from one branch to another?

You could create a patch from the commits that you want to copy and apply the patch to the destination branch.

Access non-numeric Object properties by index?

you can create an array that filled with your object fields and use an index on the array and access object properties via that

propertiesName:['pr1','pr2','pr3']

this.myObject[this.propertiesName[0]]

Fatal error: Class 'Illuminate\Foundation\Application' not found

In my situation, I didn't have the full vendor dependencies in place (composer file was messed up during original install) - so running any artisan commands caused a failure.

I was able to use the --no-scripts flag to prevent artisan from executing before it was included. Once my dependencies were in place, everything worked as expected.

composer update --no-scripts

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

Regular expression to find URLs within a string

Short and simple. I have not tested in javascript code yet but It looks it will work:

((http|ftp|https):\/\/)?(([\w.-]*)\.([\w]*))

Code on regex101.com

Code preview

Round number to nearest integer

round(value,significantDigit) is the ordinary solution, however this does not operate as one would expect from a math perspective when round values ending in 5. If the 5 is in the digit just after the one you're rounded to, these values are only sometimes rounded up as expected (i.e. 8.005 rounding to two decimal digits gives 8.01). For certain values due to the quirks of floating point math, they are rounded down instead!

i.e.

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01

Weird.

Assuming your intent is to do the traditional rounding for statistics in the sciences, this is a handy wrapper to get the round function working as expected needing to import extra stuff like Decimal.

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*5),2)

0.08

Aha! So based on this we can make a function...

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1), digits)

Basically this adds a value guaranteed to be smaller than the least given digit of the string you're trying to use round on. By adding that small quantity it preserve's round's behavior in most cases, while now ensuring if the digit inferior to the one being rounded to is 5 it rounds up, and if it is 4 it rounds down.

The approach of using 10**(-len(val)-1) was deliberate, as it the largest small number you can add to force the shift, while also ensuring that the value you add never changes the rounding even if the decimal . is missing. I could use just 10**(-len(val)) with a condiditional if (val>1) to subtract 1 more... but it's simpler to just always subtract the 1 as that won't change much the applicable range of decimal numbers this workaround can properly handle. This approach will fail if your values reaches the limits of the type, this will fail, but for nearly the entire range of valid decimal values it should work.

You can also use the decimal library to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.


Edit: Thanks Blckknght for pointing out that the 5 fringe case occurs only for certain values. Also an earlier version of this answer wasn't explicit enough that the odd rounding behavior occurs only when the digit immediately inferior to the digit you're rounding to has a 5.

How to get the background color code of an element in hex?

There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;

How to darken a background using CSS?

Just to add to what's already here, use the following:

background: -moz-linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
background: -webkit-linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
background: linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
filter: unquote("progid:DXImageTransform.Microsoft.gradient( startColorstr='#b3000000', endColorstr='#b3000000',GradientType=0 )");

...for cross-browser support of a 70% linear-gradient overlay. To brighten the image, you can change all those 0,0,0's into 255,255,255's. If 70% is a bit much, go ahead and change the .7. And, for future reference check out this: http://www.colorzilla.com/gradient-editor/

Webpack how to build production code and how to use it

You can add the plugins as suggested by @Vikramaditya. Then to generate the production build. You have to run the the command

NODE_ENV=production webpack --config ./webpack.production.config.js

If using babel, you will also need to prefix BABEL_ENV=node to the above command.

How do I print a double value with full precision using cout?

Here is a function that works for any floating-point type, not just double, and also puts the stream back the way it was found afterwards. Unfortunately it won't interact well with threads, but that's the nature of iostreams. You'll need these includes at the start of your file:

#include <limits>
#include <iostream>

Here's the function, you could it in a header file if you use it a lot:

template <class T>
void printVal(std::ostream& os, T val)
{
    auto oldFlags = os.flags();
    auto oldPrecision = os.precision();

    os.flags(oldFlags & ~std::ios_base::floatfield);
    os.precision(std::numeric_limits<T>::digits10);
    os << val;
    
    os.flags(oldFlags);
    os.precision(oldPrecision);
}

Use it like this:

double d = foo();
float f = bar();
printVal(std::cout, d);
printVal(std::cout, f);

If you want to be able to use the normal insertion << operator, you can use this extra wrapper code:

template <class T>
struct PrintValWrapper { T val; };
template <class T>
std::ostream& operator<<(std::ostream& os, PrintValWrapper<T> pvw) {
    printVal(os, pvw.val);
    return os;
}
template <class T>
PrintValWrapper<T> printIt(T val) {
    return PrintValWrapper<T>{val};
}

Now you can use it like this:

double d = foo();
float f = bar();
std::cout << "The values are: " << printIt(d) << ", " << printIt(f) << '\n';

How do I escape reserved words used as column names? MySQL/Create Table

If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.

Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:

  • Write all you SQL queries in ANSI SQL
  • Enclose them in the following MySQL specific queries:

    SET @OLD_SQL_MODE=@@SQL_MODE;
    SET SESSION SQL_MODE='ANSI';
    -- ANSI SQL queries
    SET SESSION SQL_MODE=@OLD_SQL_MODE;
    

This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.

Cannot add a project to a Tomcat server in Eclipse

I fixed this issue as adding Dynamic Web Module to Project Facets

  1. right click on project name in the Package Explorer view.
  2. select Properties
  3. Select Project Facets
  4. Activate Dynamic Web Module
  5. Click on OK

Mongoose: Find, modify, save

You could also write it a little more cleaner using updateOne & $set, plus async/await.

const updateUser = async (newUser) => {
  try {
    await User.updateOne({ username: oldUsername }, {
      $set: {
        username: newUser.username,
        password: newUser.password,
        rights: newUser.rights
      }
    })
  } catch (err) {
    console.log(err)
  }
}

Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.

Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate

Difference between Encapsulation and Abstraction

Abstraction - is the process (and result of this process) of identifying the common essential characteristics for a set of objects. One might say that Abstraction is the process of generalization: all objects under consideration are included in a superset of objects, all of which possess given properties (but are different in other respects).

Encapsulation - is the process of enclosing data and functions manipulating this data into a single unit, so that to hide the internal implementation from the outside world.

This is a general answer not related to a specific programming language (as was the question). So the answer is: abstraction and encapsulation have nothing in common. But their implementations might relate to each other (say, in Java: Encapsulation - details are hidden in a class, Abstraction - details are not present at all in a class or interface).

What are the different types of indexes, what are the benefits of each?

PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:

create index i on customers (id, name, whatever) where is_active is true;

If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:

select name from customers where is_active is true;

How may I reference the script tag that loaded the currently-executing script?

It must works at page load and when an script tag is added with javascript (ex. with ajax)

<script id="currentScript">
var $this = document.getElementById("currentScript");
$this.setAttribute("id","");
//...
</script>

Flatten list of lists

>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

Search for all occurrences of a string in a mysql database

SQLyog is GUI based solution to the problem of data search across all columns, tables and databases. One can customize search restricting it to field, table and databases.

In its Data Search feature one can search for strings just like one uses Google.

SQLyog Datasearch screenshot

How can I let a table's body scroll but keep its head fixed in place?

This caused me huge headaches trying to implement such a grid for an application of ours. I tried all the various techniques out there but they each had problems. The closest I came was using a jQuery plugin such as Flexigrid (look on http://www.ajaxrain.com for alternatives), but this doesn't seem to support 100% wide tables which is what I needed.

What I ended up doing was rolling my own; Firefox supports scrolling tbody elements so I browser sniffed and used appropriate CSS (setting height, overflow etc... ask if you want more details) to make that scroll, and then for other browsers I used two separate tables set to use table-layout: fixed which uses a sizing algorithm that is guarenteed not to overflow the stated size (normal tables will expand when content is too wide to fit). By giving both tables identical widths I was able to get their columns to line up. I wrapped the second one in a div set to scroll and with a bit of jiggery pokery with margins etc managed to get the look and feel I wanted.

Sorry if this answer sounds a bit vague in places; I'm writing quickly as I don't have much time. Leave a comment if you want me to expand any further!

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

How to uninstall pip on OSX?

Since pip is a package, pip uninstall pip Will do it.
EDIT: If that does not work, try sudo -H pip uninstall pip.

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

Cross join :Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 3 rows and table B has 2 rows, a CROSS JOIN will result in 6 rows. There is no relationship established between the two tables – you literally just produce every possible combination.

Full outer Join : A FULL OUTER JOIN is neither "left" nor "right"— it's both! It includes all the rows from both of the tables or result sets participating in the JOIN. When no matching rows exist for rows on the "left" side of the JOIN, you see Null values from the result set on the "right." Conversely, when no matching rows exist for rows on the "right" side of the JOIN, you see Null values from the result set on the "left."

html table span entire width?

Just in case you're using bootstrap 4, you can add px-0 (set left/right padding to 0) and mx-0 (set left/right margin to 0) CSS class to body tag, like below:

<body class="px-0; mx-0">
    <!--your body HTML-->
</body>

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

How to convert Milliseconds to "X mins, x seconds" in Java?

There is a problem. When milliseconds is 59999, actually it is 1 minute but it will be computed as 59 seconds and 999 milliseconds is lost.

Here is a modified version based on previous answers, which can solve this loss:

public static String formatTime(long millis) {
    long seconds = Math.round((double) millis / 1000);
    long hours = TimeUnit.SECONDS.toHours(seconds);
    if (hours > 0)
        seconds -= TimeUnit.HOURS.toSeconds(hours);
    long minutes = seconds > 0 ? TimeUnit.SECONDS.toMinutes(seconds) : 0;
    if (minutes > 0)
        seconds -= TimeUnit.MINUTES.toSeconds(minutes);
    return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
}

Temporarily change current working directory in bash to run a command

You can run the cd and the executable in a subshell by enclosing the command line in a pair of parentheses:

(cd SOME_PATH && exec_some_command)

Demo:

$ pwd
/home/abhijit
$ (cd /tmp && pwd)  # directory changed in the subshell
/tmp 
$ pwd               # parent shell's pwd is still the same
/home/abhijit

javascript multiple OR conditions in IF statement

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

How to create XML file with specific structure in Java

You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:

//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));

//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));

What is the symbol for whitespace in C?

The ASCII value of Space is 32. So you can compare your char to the octal value of 32 which is 40 or its hexadecimal value which is 20.

if(c == '\40') { ... }

or

if(c == '\x20') { ... }

Any number after the \ is assumed to be octal, if the character just after \ is not x, in which case it is considered to be a hexadecimal.

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

this.getClass().getClassLoader().getResource("...") and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Set default syntax to different filetype in Sublime Text 2

In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].

Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.

Updated 2016-04-19: As of now, this also works for Sublime Text 3.

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

Set background image in CSS using jquery

try this

 $(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Find distance between two points on map using Google Map API V2

@salman khan what Usman Kurd suggested is perfect. Only thing i found which can be corrected is that "For google maps v2 we use LatLng class. So below is the code of Usman Kurd that can be used for Google Maps v2. I checked it works perfect.

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius=6371;//radius of earth in Km         
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.asin(Math.sqrt(a));
        double valueResult= Radius*c;
        double km=valueResult/1;
        DecimalFormat newFormat = new DecimalFormat("####");
        int kmInDec =  Integer.valueOf(newFormat.format(km));
        double meter=valueResult%1000;
        int  meterInDec= Integer.valueOf(newFormat.format(meter));
        Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

        return Radius * c;
     }