Programs & Examples On #Ejb 3.1

This tag is used for question related to the session bean and message-driven bean component types of the EJB 3.1 programming model.

Finding the last index of an array

Array starts from index 0 and ends at n-1.

static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int length = arr.Length - 1;   // starts from 0 to n-1

    Console.WriteLine(length);     // this will give the last index.
    Console.Read();
}

How do I get my C# program to sleep for 50 msec?

Best of both worlds:

using System.Runtime.InteropServices;

    [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
    private static extern uint TimeBeginPeriod(uint uMilliseconds);

    [DllImport("winmm.dll", EntryPoint = "timeEndPeriod", SetLastError = true)]
    private static extern uint TimeEndPeriod(uint uMilliseconds);
    /**
     * Extremely accurate sleep is needed here to maintain performance so system resolution time is increased
     */
    private void accurateSleep(int milliseconds)
    {
        //Increase timer resolution from 20 miliseconds to 1 milisecond
        TimeBeginPeriod(1);
        Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API
        stopwatch.Start();

        while (stopwatch.ElapsedMilliseconds < milliseconds)
        {
            //So we don't burn cpu cycles
            if ((milliseconds - stopwatch.ElapsedMilliseconds) > 20)
            {
                Thread.Sleep(5);
            }
            else
            {
                Thread.Sleep(1);
            }
        }

        stopwatch.Stop();
        //Set it back to normal.
        TimeEndPeriod(1);
    }

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

How to hide navigation bar permanently in android activity?

It's my solution:

First, define boolean that indicate if navigation bar is visible or not.

boolean navigationBarVisibility = true //because it's visible when activity is created

Second create method that hide navigation bar.

private void setNavigationBarVisibility(boolean visibility){
    if(visibility){
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        navigationBarVisibility = false;
    }

    else
        navigationBarVisibility = true;
}

By default, if you click to activity after hide navigation bar, navigation bar will be visible. So we got it's state if it visible we will hide it.

Now set OnClickListener to your view. I use a surfaceview so for me:

    playerSurface.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setNavigationBarVisibility(navigationBarVisibility);
        }
    });

Also, we must call this method when activity is launched. Because we want hide it at the beginning.

        setNavigationBarVisibility(navigationBarVisibility);

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

Why is an OPTIONS request sent and can I disable it?

There is maybe a solution (but i didnt test it) : you could use CSP (Content Security Policy) to enable your remote domain and browsers will maybe skip the CORS OPTIONS request verification.

I if find some time, I will test that and update this post !

CSP : https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Content-Security-Policy

CSP Specification : https://www.w3.org/TR/CSP/

No input file specified

In my case, I fixed it by butting the rules inside a LocationMatch Directive

<LocationMatch "^/.">
    #your rewrite rules here
</LocationMatch>

/. matches any location

I have the rewrite rules inside one of the .conf files of Apache NOT .htaccess file.

I don't know why this worked with me, this is my current setup

  • Apache version 2.4
  • PHP 7.1
  • OS Centos 7
  • PHP-FPM

CKEditor automatically strips classes from div

Following is the complete example for CKEDITOR 4.x :

HTML

<textarea name="post_content" id="post_content" class="form-control"></textarea>

SCRIPT

CKEDITOR.replace('post_content', {
   allowedContent:true,
});

The above code will allow all tags in the editor.

For more Detail : CK EDITOR Allowed Content Rules

How do I return a string from a regex match in python?

You should use re.MatchObject.group(0). Like

imtag = re.match(r'<img.*?>', line).group(0)

Edit:

You also might be better off doing something like

imgtag  = re.match(r'<img.*?>',line)
if imtag:
    print("yo it's a {}".format(imgtag.group(0)))

to eliminate all the Nones.

Python creating a dictionary of lists

You can use setdefault:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d.setdefault(j, []).append(i)

print d  # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}

The rather oddly-named setdefault function says "Get the value with this key, or if that key isn't there, add this value and then return it."

As others have rightly pointed out, defaultdict is a better and more modern choice. setdefault is still useful in older versions of Python (prior to 2.5).

Setting a JPA timestamp column to be generated by the database?

I'm posting this for people searching for an answer when using MySQL and Java Spring Boot JPA, like @immanuelRocha says, only have too @CreationTimeStamp to the @Column in Spring, and in MySQL set the default value to "CURRENT_TIMESTAMP".

In Spring add just the line :

_x000D_
_x000D_
@Column(name = "insert_date")_x000D_
@CreationTimestamp_x000D_
private Timestamp insert_date;
_x000D_
_x000D_
_x000D_

MS SQL compare dates?

Try This:

BEGIN

declare @Date1 datetime
declare @Date2 datetime

declare @chkYear int
declare @chkMonth int
declare @chkDay int
declare @chkHour int
declare @chkMinute int
declare @chkSecond int
declare @chkMiliSecond int

set @Date1='2010-12-31 15:13:48.593'
set @Date2='2010-12-31 00:00:00.000'

set @chkYear=datediff(yyyy,@Date1,@Date2)
set @chkMonth=datediff(mm,@Date1,@Date2)
set @chkDay=datediff(dd,@Date1,@Date2)
set @chkHour=datediff(hh,@Date1,@Date2)
set @chkMinute=datediff(mi,@Date1,@Date2)
set @chkSecond=datediff(ss,@Date1,@Date2)
set @chkMiliSecond=datediff(ms,@Date1,@Date2)

if @chkYear=0 AND @chkMonth=0 AND @chkDay=0 AND @chkHour=0 AND @chkMinute=0 AND @chkSecond=0 AND @chkMiliSecond=0
    Begin
        Print 'Both Date is Same'
    end
else
    Begin
        Print 'Both Date is not Same'
    end
End

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

How to take a screenshot programmatically on iOS

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *imageData = UIImageJPEGRepresentation(image, 1.0 ); //you can use PNG too
[imageData writeToFile:@"image1.jpeg" atomically:YES];

How to read/write from/to file using Go?

With newer Go versions, reading/writing to/from file is easy. To read from a file:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    data, err := ioutil.ReadFile("text.txt")
    if err != nil {
        return
    }
    fmt.Println(string(data))
}

To write to a file:

package main

import "os"

func main() {
    file, err := os.Create("text.txt")
    if err != nil {
        return
    }
    defer file.Close()

    file.WriteString("test\nhello")
}

This will overwrite the content of a file (create a new file if it was not there).

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

In php, is 0 treated as empty?

I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.

A snippet:

Expression      | empty($x)
----------------+--------
$x = "";        | true    
$x = null       | true    
var $x;         | true    
$x is undefined | true    
$x = array();   | true    
$x = false;     | true    
$x = true;      | false   
$x = 1;         | false   
$x = 42;        | false   
$x = 0;         | true    
$x = -1;        | false   
$x = "1";       | false   
$x = "0";       | true    
$x = "-1";      | false   
$x = "php";     | false   
$x = "true";    | false   
$x = "false";   | false   

Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure

Is embedding background image data into CSS as Base64 good or bad practice?

This answer is out of date and shouldn't be used.

1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network

2) HTTP2 multiplexes https://http2.github.io/faq/#why-is-http2-multiplexed

"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.

Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.

http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/

"A referral was returned from the server" exception when accessing AD from C#

This is the answer for the question.Reason for the cause is my LDAP string was wrong.

    try
    {
        string adServer = ConfigurationManager.AppSettings["Server"];
        string adDomain = ConfigurationManager.AppSettings["Domain"];
        string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
        string password = ConfigurationManager.AppSettings["Password"];
        string[] dc = adDomain.Split('.');
        string dcAdDomain = string.Empty;

        foreach (string item in dc)
        {
            if (dc[dc.Length - 1].Equals(item))
                dcAdDomain = dcAdDomain + "DC=" + item;
            else
                dcAdDomain = dcAdDomain + "DC=" + item + ",";
        }

        DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);

        DirectorySearcher ds = new DirectorySearcher(de);

        ds.SearchScope = SearchScope.Subtree;

        ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

        if (ds.FindOne() != null)
            return true;
    }
    catch (Exception ex)
    {
        ExLog(ex);
    }
    return false;

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

Get the contents of a table row with a button click

function useAdress () { 
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};

then on your button:

onclick="useAdress()"

How to set a class attribute to a Symfony2 form input

You can do it with FormBuilder. Add this to the array in your FormBuilder:

'attr'=> array('class'=>'span2')

What is the string concatenation operator in Oracle?

DECLARE
     a      VARCHAR2(30);
     b      VARCHAR2(30);
     c      VARCHAR2(30);
 BEGIN
      a  := ' Abc '; 
      b  := ' def ';
      c  := a || b;
 DBMS_OUTPUT.PUT_LINE(c);  
   END;

output:: Abc def

Search input with an icon Bootstrap 4

you can also do in this way using input-group

<div class="input-group">
  <input class="form-control"
         placeholder="I can help you to find anything you want!">
  <div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>

codeply

What version of JBoss I am running?

If you know the location of installed jboss folder then simply open it and look for version.txt file.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.

I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.

LINK: maxConnection setting may not work even autoConfig = false in ASP.NET

Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.

LINK: <remove> Element for connectionManagement (Network Settings)

Hope it helps someone.

Count distinct values

You can use this:

select count(customer) as count, pets
from table
group by pets

How to truncate the time on a DateTime object in Python?

To get a midnight corresponding to a given datetime object, you could use datetime.combine() method:

>>> from datetime import datetime, time
>>> dt = datetime.utcnow()
>>> dt.date()
datetime.date(2015, 2, 3)
>>> datetime.combine(dt, time.min)
datetime.datetime(2015, 2, 3, 0, 0)

The advantage compared to the .replace() method is that datetime.combine()-based solution will continue to work even if datetime module introduces the nanoseconds support.

tzinfo can be preserved if necessary but the utc offset may be different at midnight e.g., due to a DST transition and therefore a naive solution (setting tzinfo time attribute) may fail. See How do I get the UTC time of “midnight” for a given timezone?

Storing Python dictionaries

Also see the speeded-up package ujson:

import ujson

with open('data.json', 'wb') as fp:
    ujson.dump(data, fp)

How to change the author and committer name and e-mail of multiple commits in Git?

I want to add my Example too. I want to create a bash_function with given parameter.

this works in mint-linux-17.3

# $1 => email to change, $2 => new_name, $3 => new E-Mail

function git_change_user_config_for_commit {

 # defaults
 WRONG_EMAIL=${1:-"[email protected]"}
 NEW_NAME=${2:-"your name"}
 NEW_EMAIL=${3:-"[email protected]"}

 git filter-branch -f --env-filter "
  if [ \$GIT_COMMITTER_EMAIL = '$WRONG_EMAIL' ]; then
    export GIT_COMMITTER_NAME='$NEW_NAME'
    export GIT_COMMITTER_EMAIL='$NEW_EMAIL'
  fi
  if [ \$GIT_AUTHOR_EMAIL = '$WRONG_EMAIL' ]; then
    export GIT_AUTHOR_NAME='$NEW_NAME'
    export GIT_AUTHOR_EMAIL='$NEW_EMAIL'
  fi
 " --tag-name-filter cat -- --branches --tags;
}

How to delete session cookie in Postman?

Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.

enter image description here

How to Clear Console in Java?

You can easily implement clrscr() using simple for loop printing "\b".

Grep characters before and after match?

grep -E -o ".{0,5}test_pattern.{0,5}" test.txt 

This will match up to 5 characters before and after your pattern. The -o switch tells grep to only show the match and -E to use an extended regular expression. Make sure to put the quotes around your expression, else it might be interpreted by the shell.

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

jquery - is not a function error

I solved it by renaming my function.

Changed

function editForm(value)

to

function editTheForm(value)

Works perfectly.

Ordering by specific field value first

SELECT * FROM cars_new WHERE status = '1' and car_hide !='1' and cname IN ('Executive Car','Saloon','MPV+','MPV5') ORDER BY FIELD(cname, 'Executive Car', 'Saloon','MPV+','mpv5')

Could not complete the operation due to error 80020101. IE

All the error 80020101 means is that there was an error, of some sort, while evaluating JavaScript. If you load that JavaScript via Ajax, the evaluation process is particularly strict.

Sometimes removing // will fix the issue, but the inverse is not true... the issue is not always caused by //.

Look at the exact JavaScript being returned by your Ajax call and look for any issues in that script. For more details see a great writeup here

http://mattwhite.me/blog/2010/4/21/tracking-down-error-80020101-in-internet-exploder.html

Use CSS to remove the space between images

Make them display: block in your CSS.

How to export iTerm2 Profiles

Preferences -> General -> Load preferences from a custom folder or URL

First time you choose this, it will automatically save a preferences file into this folder called "com.googlecode.iterm2.plist"

When to use dynamic vs. static libraries

We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages:

  • slow startup (> 10 seconds)
  • DLL's had to be versioned, since windows loads modules on uniqueness of names. Own written components would otherwise get the wrong version of the DLL (i.e. the one already loaded instead of its own distributed set)
  • optimizer can only optimize within DLL boundaries. For example the optimizer tries to place frequently used data and code next to each other, but this will not work across DLL boundaries

Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with:

  • exe uses shared_lib1, shared_lib2
  • shared_lib1 use shared_lib2
  • shared_lib2

The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question?

Identifying and removing null characters in UNIX

A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv to convert it to UTF-8.

Get value from SimpleXMLElement Object

For me its easier to use arrays than objects,

So, I convert an Xml-Object,

$xml = simplexml_load_file('xml_file.xml');    
$json_string = json_encode($xml);    
$result_array = json_decode($json_string, TRUE);

Easy way to convert Iterable to Collection

Since RxJava is a hammer and this kinda looks like a nail, you can do

Observable.from(iterable).toList().toBlocking().single();

Ruby: kind_of? vs. instance_of? vs. is_a?

I also wouldn't call two many (is_a? and kind_of? are aliases of the same method), but if you want to see more possibilities, turn your attention to #class method:

A = Class.new
B = Class.new A

a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class

How to get Url Hash (#) from server side

RFC 2396 section 4.1:

When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.

(emphasis added)

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

The short-circuiting boolean operators (and, or) can't be overriden because there is no satisfying way to do this without introducing new language features or sacrificing short circuiting. As you may or may not know, they evaluate the first operand for its truth value, and depending on that value, either evaluate and return the second argument, or don't evaluate the second argument and return the first:

something_true and x -> x
something_false and x -> something_false
something_true or x -> something_true
something_false or x -> x

Note that the (result of evaluating the) actual operand is returned, not truth value thereof.

The only way to customize their behavior is to override __nonzero__ (renamed to __bool__ in Python 3), so you can affect which operand gets returned, but not return something different. Lists (and other collections) are defined to be "truthy" when they contain anything at all, and "falsey" when they are empty.

NumPy arrays reject that notion: For the use cases they aim at, two different notions of truth are common: (1) Whether any element is true, and (2) whether all elements are true. Since these two are completely (and silently) incompatible, and neither is clearly more correct or more common, NumPy refuses to guess and requires you to explicitly use .any() or .all().

& and | (and not, by the way) can be fully overriden, as they don't short circuit. They can return anything at all when overriden, and NumPy makes good use of that to do element-wise operations, as they do with practically any other scalar operation. Lists, on the other hand, don't broadcast operations across their elements. Just as mylist1 - mylist2 doesn't mean anything and mylist1 + mylist2 means something completely different, there is no & operator for lists.

How do I start PowerShell from Windows Explorer?

There's a Windows Explorer extension made by the dude who makes tools for SVN that will at least open a command prompt window.

I haven't tried it yet, so I don't know if it'll do PowerShell, but I wanted to share the love with my Stack Overflow brethren:

http://tools.tortoisesvn.net/StExBar

Keyboard shortcuts with jQuery

There is a new version of hotKeys.js that works with 1.10+ version of jQuery. It is small, 100 line javascript file. 4kb or just 2kb minified. Here are some Simple usage examples are :

$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);

$('#myBody').hotKey({ key: 'f4' }, doSomethingElse);

$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
            doSomethingWithaParameter('Daniel');
        });

$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);

Clone the repo from github : https://github.com/realdanielbyrne/HoyKeys.git or go to the github repo page https://github.com/realdanielbyrne/HoyKeys or fork and contribute.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

Make sure you verify your setting for "Prefer 32-bit". In my case Visual Studio 2012 had this setting checked by default. Trying to use anything from an external DLL failed until I unchecked "Prefer 32-bit".

enter image description here

Iterating through list of list in Python

This can also be achieved with itertools.chain.from_iterable which will flatten the consecutive iterables:

import itertools
for item in itertools.chain.from_iterable(iterables):
    # do something with item    

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

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

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!

FormsAuthentication.SignOut() does not log the user out

For MVC this works for me:

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return Redirect(FormsAuthentication.GetRedirectUrl(User.Identity.Name, true));
        }

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

add Shadow on UIView using swift 3

We can apply drop shadow by following way also

    cell.view1.layer.masksToBounds = false
    cell.view1.layer.shadowColor = UIColor.lightGray.cgColor
    cell.view1.backgroundColor = UIColor.white
    cell.view1.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
    cell.view1.layer.shadowOpacity = 0.5

Result will be : http://prntscr.com/nhhv2s

How to find length of a string array?

Since car has not been initialized, it has no length, its value is null. However, the compiler won't even allow you to compile that code as is, throwing the following error: variable car might not have been initialized.

You need to initialize it first, and then you can use .length:

String car[] = new String[] { "BMW", "Bentley" };
System.out.println(car.length);

If you need to initialize an empty array, you can use the following:

String car[] = new String[] { }; // or simply String car[] = { };
System.out.println(car.length);

If you need to initialize it with a specific size, in order to fill certain positions, you can use the following:

String car[] = new String[3]; // initialize a String[] with length 3
System.out.println(car.length); // 3
car[0] = "BMW";
System.out.println(car.length); // 3

However, I'd recommend that you use a List instead, if you intend to add elements to it:

List<String> cars = new ArrayList<String>();
System.out.println(cars.size()); // 0
cars.add("BMW");
System.out.println(cars.size()); // 1

How to change an Android app's name?

If you're using android studio an item is under your strings.xml

<string name="app_name">BareBoneProject</string>

It's better to change the name here because you might have used this string somewhere.Or maybe a library or something has used it.That's it.Just build and run and you'll get new name.Remember this won't change the package name or anything else.

Easiest way to copy a single file from host to Vagrant guest?

If you are restrained from having the files in your directory, you can run this code in a script file from the Host machine.

#!/bin/sh
OPTIONS=`vagrant ssh-config | awk -v ORS=' ' '{print "-o " $1 "=" $2}'`

scp ${OPTIONS} /File/To/Copy vagrant@YourServer:/Where/To/Put/File

In this setup, you only need to change /File/To/Copy to the file or files you want to copy and then /Where/To/Put/File is the location on the VM you wish to have the files copied to.

If you create this file and call it copyToServer.sh you can then run the sh command to push those files.

sh ./copyToServer.sh

As a final note, you cannot run this code as a provisioner because that runs on the Guest server, while this code runs from the Host.

Move an array element from one array position to another

One approach would be to create a new array with the pieces in the order you want, using the slice method.

Example

var arr = [ 'a', 'b', 'c', 'd', 'e'];
var arr2 = arr.slice(0,1).concat( ['d'] ).concat( arr.slice(2,4) ).concat( arr.slice(4) );
  • arr.slice(0,1) gives you ['a']
  • arr.slice(2,4) gives you ['b', 'c']
  • arr.slice(4) gives you ['e']

History or log of commands executed in Git

git will show changes in commits that affect the index, such as git rm. It does not store a log of all git commands you execute.

However, a large number of git commands affect the index in some way, such as creating a new branch. These changes will show up in the commit history, which you can view with git log.

However, there are destructive changes that git can't track, such as git reset.

So, to answer your question, git does not store an absolute history of git commands you've executed in a repository. However, it is often possible to interpolate what command you've executed via the commit history.

How can I create a dynamically sized array of structs?

Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.

Getting a browser's name client-side

JavaScript side - you can get browser name like these ways...

if(window.navigator.appName == "") OR if(window.navigator.userAgent == "")

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

What i did was i commented out the

props.put("mail.smtp.starttls.enable","true"); 

Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

For Mac users(OS X El Capitan):

You need to kill the port that localhost:8080 is running on.
To do this, you need to do two commands in the terminal :N

sudo lsof -i tcp:8080

kill -15 PID 

NB! PID IS A NUMBER PROVIDED BY THE FIRST COMMAND.

The first command gives you the PID for the localhost:8080.
Replace the PID in the second command with the PID that the first command gives you to kill the process running on localhost:8080.

How to implement a ViewPager with different Fragments / Layouts

Create an array of Views and apply it to: container.addView(viewarr[position]);

public class Layoutes extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    Layoutes(Context context){
        this.context=context;
    }
    int layoutes[]={R.layout.one,R.layout.two,R.layout.three};
    @Override
    public int getCount() {
        return layoutes.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position){
        layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View one=layoutInflater.inflate(R.layout.one,container,false);
        View two=layoutInflater.inflate(R.layout.two,container,false);
        View three=layoutInflater.inflate(R.layout.three,container,false);
        View viewarr[]={one,two,three};
        container.addView(viewarr[position]);
        return viewarr[position];
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout) object);
    }

}

How do I find out what type each object is in a ArrayList<Object>?

In Java just use the instanceof operator. This will also take care of subclasses.

ArrayList<Object> listOfObjects = new ArrayList<Object>();
for(Object obj: listOfObjects){
   if(obj instanceof String){
   }else if(obj instanceof Integer){
   }etc...
}

What is the largest possible heap size with a 64-bit JVM?

Windows imposes a memory limit per process, you can see what it is for each version here

See:

User-mode virtual address space for each 64-bit process; With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default): x64: 8 TB Intel IPF: 7 TB 2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared

What is the point of the diamond operator (<>) in Java 7?

In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?

  1. No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.
  2. The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.

IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.

Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as

package 7 com.example;

could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

Simple way to get element by id within a div tag?

var x = document.getElementById("parent").querySelector("#child");
// don't forget a #

or

var x = document.querySelector("#parent").querySelector("#child");

or

var x = document.querySelector("#parent #child");

or

var x = document.querySelector("#parent");
var y = x.querySelector("#child");

eg.

var x = document.querySelector("#div1").querySelector("#edit2");

How to SELECT a dropdown list item by value programmatically

I prefer

if(ddl.Items.FindByValue(string) != null)
{
    ddl.Items.FindByValue(string).Selected = true;
}

Replace ddl with the dropdownlist ID and string with your string variable name or value.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

How to select between brackets (or quotes or ...) in Vim?

For selecting within single quotes use vi'.

For selecting within parenthesis use vi(.

phpMyAdmin - The MySQL Extension is Missing

In my case I had to install the extension:

yum install php php-mysql httpd

and then restart apache:

service httpd restart

That solved the problem.

How to convert a DataTable to a string in C#?

Or, change the app to WinForms, use grid and bind DataTable to grid. If it is a demo/sample app.

Wi-Fi Direct and iOS Support

The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

  • Wireless Accessory Configuration (WAC)
  • HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

jquery how to catch enter key and change event to tab

$('input').live("keypress", function(e) {
            /* ENTER PRESSED*/
            if (e.keyCode == 13) {
                /* FOCUS ELEMENT */
                var inputs = $(this).parents("form").eq(0).find(":input:visible");
                var idx = inputs.index(this);

                if (idx == inputs.length - 1) {
                    inputs[0].select()
                } else {
                    inputs[idx + 1].focus(); //  handles submit buttons
                    inputs[idx + 1].select();
                }
                return false;
            }
        });

visible input cann't be focused.

After submitting a POST form open a new window showing the result

I know this basic method:

1)

<input type=”image” src=”submit.png”> (in any place)

2)

<form name=”print”>
<input type=”hidden” name=”a” value=”<?= $a ?>”>
<input type=”hidden” name=”b” value=”<?= $b ?>”>
<input type=”hidden” name=”c” value=”<?= $c ?>”>
</form>

3)

<script>
$(‘#submit’).click(function(){
    open(”,”results”);
    with(document.print)
    {
        method = “POST”;
        action = “results.php”;
        target = “results”;
        submit();
    }
});
</script>

Works!

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

In addition to the answer of eldos I also needed gcc in CentOS 7:

yum install libcurl-devel gcc

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

How to initialize java.util.date to empty

Try initializing with null value.

private java.util.Date date2 = null;

Also private java.util.Date date2 = ""; will not work as "" is a string.

How to listen to route changes in react router v4?

import React, { useEffect } from 'react';
import { useLocation } from 'react-router';

function MyApp() {

  const location = useLocation();

  useEffect(() => {
      console.log('route has been changed');
      ...your code
  },[location.pathname]);

}

with hooks

Remove all occurrences of char from string

If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.

StringUtils.remove("TextX Xto modifyX", 'X');

Programmatically read from STDIN or input file in Perl

You need to use <> operator:

while (<>) {
    print $_; # or simply "print;"
}

Which can be compacted to:

print while (<>);

Arbitrary file:

open F, "<file.txt" or die $!;
while (<F>) {
    print $_;
}
close F;

Is it possible to import a whole directory in sass using @import?

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

is there a post render callback for Angular JS directive?

May be am late to answer this question. But still someone may get benefit out of my answer.

I had similar issue and in my case I can not change the directive since, it is a library and change a code of the library is not a good practice. So what I did was use a variable to wait for page load and use ng-if inside my html to wait render the particular element.

In my controller:

$scope.render=false;

//this will fire after load the the page

angular.element(document).ready(function() {
    $scope.render=true;
});

In my html (in my case html component is a canvas)

<canvas ng-if="render"> </canvas>

How to make exe files from a node.js app?

By default, Windows associates .js files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js file in Explorer), the script is executed by wscript.exe.

This may be solving a local problem with a global setting, but you could associate .js files with node.exe instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.

Of course, if—like me—you've associated .js files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js files, although this alternative doesn't solve your command-line needs.


The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:

"C:\Program Files (x86)\nodejs\node.exe" app.js %*

Another alternative is this very simple C# app which will start Node using its own filename + .js as the script to run, and pass along any command line arguments.

class Program
{
    static void Main(string[] args)
    {
        var info = System.Diagnostics.Process.GetCurrentProcess();
        var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
        proc.UseShellExecute = false;
        System.Diagnostics.Process.Start(proc);
    }
}

So if you name the resulting EXE "app.exe", you can type app arg1 ... and Node will be started with the command line "app.js" arg1 .... Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.

Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.

Angular2 - Focusing a textbox on component load

Directive for autoFocus first field

_x000D_
_x000D_
import {_x000D_
  Directive,_x000D_
  ElementRef,_x000D_
  AfterViewInit_x000D_
} from "@angular/core";_x000D_
_x000D_
@Directive({_x000D_
  selector: "[appFocusFirstEmptyInput]"_x000D_
})_x000D_
export class FocusFirstEmptyInputDirective implements AfterViewInit {_x000D_
  constructor(private el: ElementRef) {}_x000D_
  ngAfterViewInit(): void {_x000D_
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");_x000D_
    if (invalidControl) {_x000D_
      invalidControl.focus();_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

html "data-" attribute as javascript parameter

JS:

function fun(obj) {
    var uid= $(obj).data('uid');
    var name= $(obj).data('name');
    var value= $(obj).data('value');
}

Meaning of tilde in Linux bash (not home directory)

Those are the home directories of the users. Try cd ~(your username), for example.

opening a window form from another form programmatically

You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you : Accessing UI Control from BackgroundWorker Thread

PHP: How to send HTTP response code?

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

Assembling the response code on your own (PHP >= 4.0)

The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

header("HTTP/1.1 200 OK");

However, this requires special treatment for (Fast)CGI PHP:

$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note: php_sapi_name() requires PHP 4.0.1

3rd argument to header function (PHP >= 4.3)

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

http_response_code function (PHP >= 5.4)

The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

http_response_code(404);

That's all.

Compatibility

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...

// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
    function http_response_code($newcode = NULL)
    {
        static $code = 200;
        if($newcode !== NULL)
        {
            header('X-PHP-Response-Code: '.$newcode, true, $newcode);
            if(!headers_sent())
                $code = $newcode;
        }       
        return $code;
    }
}

Document Root PHP

Yes, on the server side $_SERVER['DOCUMENT_ROOT'] is equivalent to / on the client side.

For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png" will be the string /var/www/html/images/thumbnail.png on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png

No, in other words the value of $_SERVER['DOCUMENT_ROOT'] is not / rather it is the server's local path to what the server shows the client at example.com/

note: $_SERVER['DOCUMENT_ROOT'] does not include a trailing /

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Easiest:
1. Open phpMyAdmin
2. On the left click database name
3. On the top right corner find "Designer" tab

All constraints will be shown there.

Multiline string literal in C#

If you don't want spaces/newlines, string addition seems to work:

var myString = String.Format(
  "hello " + 
  "world" +
  " i am {0}" +
  " and I like {1}.",
  animalType,
  animalPreferenceType
);
// hello world i am a pony and I like other ponies.

You can run the above here if you like.

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

When calling a function that is declared with throws in Swift, you must annotate the function call site with try or try!. For example, given a throwing function:

func willOnlyThrowIfTrue(value: Bool) throws {
  if value { throw someError }
}

this function can be called like:

func foo(value: Bool) throws {
  try willOnlyThrowIfTrue(value)
}

Here we annotate the call with try, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws, because this function could throw an exception (i.e., when willOnlyThrowIfTrue() throws, then foo will automatically rethrow the exception upwards.

If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!.

func bar() {
  try! willOnlyThrowIfTrue(false)
}

This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.

try! is enforced at runtime: if you use try! and the function does end up throwing, then your program's execution will be terminated with a runtime error.

Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()), or sometimes via defered code.

func baz(value: Bool) throws {

  var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
  var data = NSData(contentsOfFile:filePath)

  try willOnlyThrowIfTrue(value)

  // data and filePath automatically cleaned up, even when an exception occurs.
}

If for whatever reason you have clean up code that needs to run but isn't in a deinit() function, you can use defer.

func qux(value: Bool) throws {
  defer {
    print("this code runs when the function exits, even when it exits by an exception")
  }

  try willOnlyThrowIfTrue(value)
}

Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit() or defer. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.

Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.

Handling exceptions is done via catch statements.

func quux(value: Bool) {
  do {
    try willOnlyThrowIfTrue(value)
  } catch {
    // handle error
  }
}

You can have multiple catch statements, each catching a different kind of exception.

  do {
    try someFunctionThatThowsDifferentExceptions()
  } catch MyErrorType.errorA {
    // handle errorA
  } catch MyErrorType.errorB {
    // handle errorB
  } catch {
    // handle other errors
  }

For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.

For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).

How to check whether input value is integer or float?

You can use RoundingMode.#UNNECESSARY if you want/accept exception thrown otherwise

new BigDecimal(value).setScale(2, RoundingMode.UNNECESSARY);

If this rounding mode is specified on an operation that yields an inexact result, an ArithmeticException is thrown.

Exception if not integer value:

java.lang.ArithmeticException: Rounding necessary

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How to get 2 digit year w/ Javascript?

var currentYear =  (new Date()).getFullYear();   
var twoLastDigits = currentYear%100;

var formatedTwoLastDigits = "";

if (twoLastDigits <10 ) {
    formatedTwoLastDigits = "0" + twoLastDigits;
} else {
    formatedTwoLastDigits = "" + twoLastDigits;
}

How do I convert a numpy array to (and display) an image?

How to show images stored in numpy array with example (works in Jupyter notebook)

I know there are simpler answers but this one will give you understanding of how images are actually drawn from a numpy array.

Load example

from sklearn.datasets import load_digits
digits = load_digits()
digits.images.shape   #this will give you (1797, 8, 8). 1797 images, each 8 x 8 in size

Display array of one image

digits.images[0]
array([[ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.],
       [ 0.,  0., 13., 15., 10., 15.,  5.,  0.],
       [ 0.,  3., 15.,  2.,  0., 11.,  8.,  0.],
       [ 0.,  4., 12.,  0.,  0.,  8.,  8.,  0.],
       [ 0.,  5.,  8.,  0.,  0.,  9.,  8.,  0.],
       [ 0.,  4., 11.,  0.,  1., 12.,  7.,  0.],
       [ 0.,  2., 14.,  5., 10., 12.,  0.,  0.],
       [ 0.,  0.,  6., 13., 10.,  0.,  0.,  0.]])

Create empty 10 x 10 subplots for visualizing 100 images

import matplotlib.pyplot as plt
fig, axes = plt.subplots(10,10, figsize=(8,8))

Plotting 100 images

for i,ax in enumerate(axes.flat):
    ax.imshow(digits.images[i])

Result:

enter image description here

What does axes.flat do? It creates a numpy enumerator so you can iterate over axis in order to draw objects on them. Example:

import numpy as np
x = np.arange(6).reshape(2,3)
x.flat
for item in (x.flat):
    print (item, end=' ')

How to extract year and month from date in PostgreSQL without using to_char() function?

to_char(timestamp, 'YYYY-MM')

You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.


An Analogy...

Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. Give me a ring back when you've got the information!

At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.


Imagine if the conversation had gone like this instead;

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. I'll wait.

And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.


This is asynchronous vs. synchronous behavior

This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).

Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.

var outerScopeVar;    
var img = document.createElement('img');

// Here we register the callback function.
img.onload = function() {
    // Code within this function will be executed once the image has loaded.
    outerScopeVar = this.width;
};

// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';
alert(outerScopeVar);

In the code above, we're asking JavaScript to load lolcat.png, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar).

This is why we see the alert showing undefined; since the alert() is processed immediately, rather than after the image has been loaded.

In order to fix our code, all we have to do is move the alert(outerScopeVar) code into the callback function. As a consequence of this, we no longer need the outerScopeVar variable declared as a global variable.

var img = document.createElement('img');

img.onload = function() {
    var localScopeVar = this.width;
    alert(localScopeVar);
};

img.src = 'lolcat.png';

You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.

Therefore, in all of our examples, the function() { /* Do something */ } is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!

* Technically you can use eval() as well, but eval() is evil for this purpose


How do I keep my caller waiting?

You might currently have some code similar to this;

function getWidthOfImage(src) {
    var outerScopeVar;

    var img = document.createElement('img');
    img.onload = function() {
        outerScopeVar = this.width;
    };
    img.src = src;
    return outerScopeVar;
}

var width = getWidthOfImage('lolcat.png');
alert(width);

However, we now know that the return outerScopeVar happens immediately; before the onload callback function has updated the variable. This leads to getWidthOfImage() returning undefined, and undefined being alerted.

To fix this, we need to allow the function calling getWidthOfImage() to register a callback, then move the alert'ing of the width to be within that callback;

function getWidthOfImage(src, cb) {     
    var img = document.createElement('img');
    img.onload = function() {
        cb(this.width);
    };
    img.src = src;
}

getWidthOfImage('lolcat.png', function (width) {
    alert(width);
});

... as before, note that we've been able to remove the global variables (in this case width).

How to set Java SDK path in AndroidStudio?

This problem arises due to incompatible JDK version. Download and install latest JDK(currently its 8) from java official site in case you are using previous versions. Then in Android Studio go to File->Project Structure->SDK location -> JDK location and set it to 'C:\Program Files\Java\jdk1.8.0_121' (Default location of JDK). Gradle sync your project and you are all set...

Multiline TextView in Android?

Just add textview in ScrollView

<ScrollView
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:layout_marginLeft="15dp"
           android:layout_marginRight="15dp"
           android:layout_marginTop="20dp"
           android:fillViewport="true">

           <TextView
               android:id="@+id/txtquestion"
               android:layout_width="fill_parent"
               android:layout_height="match_parent"
               android:background="@drawable/abs__dialog_full_holo_light"
               android:lines="20"
               android:scrollHorizontally="false"
               android:scrollbars="vertical"
               android:textSize="15sp" />

       </ScrollView>

How do I add an active class to a Link from React Router?

The answer by Vijey has a bit of a problem when you're using react-redux for state management and some of the parent components are 'connected' to the redux store. The activeClassName is applied to Link only when the page is refreshed, and is not dynamically applied as the current route changes.

This is to do with the react-redux's connect function, as it suppresses context updates. To disable suppression of context updates, you can set pure: false when calling the connect() method like this:

//your component which has the custom NavLink as its child. 
//(this component may be the any component from the list of 
//parents and grandparents) eg., header

function mapStateToProps(state) {
  return { someprops: state.someprops }
}

export default connect(mapStateToProps, null, null, {
  pure: false
})(Header);

Check the issue here: reactjs#470

Check pure: false documentation here: docs

How to use onSavedInstanceState example please

This is for extra information.

Imagine this scenario

  1. ActivityA launch ActivityB.
  2. ActivityB launch a new ActivityAPrime by

    Intent intent = new Intent(getApplicationContext(), ActivityA.class);
    startActivity(intent);
    
  3. ActivityAPrime has no relationship with ActivityA.
    In this case the Bundle in ActivityAPrime.onCreate() will be null.

If ActivityA and ActivityAPrime should be the same activity instead of different activities, ActivityB should call finish() than using startActivity().

How can I get browser to prompt to save password?

I had similar problem, login was done with ajax, but browsers (firefox, chrome, safari and IE 7-10) would not offer to save password if form (#loginForm) is submitted with ajax.

As a SOLUTION I have added hidden submit input (#loginFormHiddenSubmit) to form that was submitted by ajax and after ajax call would return success I would trigger a click to hidden submit input. The page any way needed to refreshed. The click can be triggered with:

jQuery('#loginFormHiddenSubmit').click();

Reason why I have added hidden submit button is because:

jQuery('#loginForm').submit();

would not offer to save password in IE (although it has worked in other browsers).

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

How can I make all images of different height and width the same via CSS?

Updated answer (No IE11 support)

_x000D_
_x000D_
img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    object-fit: cover;_x000D_
}
_x000D_
<img src="http://i.imgur.com/tI5jq2c.jpg">_x000D_
<img src="http://i.imgur.com/37w80TG.jpg">_x000D_
<img src="http://i.imgur.com/B1MCOtx.jpg">
_x000D_
_x000D_
_x000D_

Original answer

_x000D_
_x000D_
.img {_x000D_
    float: left;_x000D_
    width:  100px;_x000D_
    height: 100px;_x000D_
    background-size: cover;_x000D_
}
_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/tI5jq2c.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/37w80TG.jpg');"></div>_x000D_
<div class="img" style="background-image:url('http://i.imgur.com/B1MCOtx.jpg');"></div>
_x000D_
_x000D_
_x000D_

Select records from today, this week, this month php mysql

A better solution for "today" is:

SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())

What's the valid way to include an image with no src?

I haven't done this in a while, but I had to go through this same thing once.

<img src="about:blank" alt="" />

Is my favorite - the //:0 one implies that you'll try to make an HTTP/HTTPS connection to the origin server on port zero (the tcpmux port?) - which is probably harmless, but I'd rather not do anyways. Heck, the browser may see the port zero and not even send a request. But I'd still rather it not be specified that way when that's probably not what you mean.

Anyways, the rendering of about:blank is actually very fast in all browsers that I tested. I just threw it into the W3C validator and it didn't complain, so it might even be valid.

Edit: Don't do that; it doesn't work on all browsers (it will show a 'broken image' icon as pointed out in the comments for this answer). Use the <img src='data:... solution below. Or if you don't care about validity, but still want to avoid superfluous requests to your server, you can do <img alt="" /> with no src attribute. But that is INVALID HTML so pick that carefully.

Test Page showing a whole bunch of different methods: http://desk.nu/blank_image.php - served with all kinds of different doctypes and content-types. - as mentioned in the comments below, use Mark Ormston's new test page at: http://memso.com/Test/BlankImage.html

Create XML file using java

Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
        // root element


Element rootElement = doc.createElement("words");
            doc.appendChild(rootElement);
while (ptbt.hasNext()) {
                CoreLabel label = ptbt.next();
                System.out.println(label);

                m = r1.matcher(label.toString());
                //System.out.println(m.find());
                if (m.find() == true) {
                    Element w = doc.createElement("word");                  
                    w.appendChild(doc.createTextNode(label.toString()));
                    rootElement.appendChild(w);
                }

TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
        transformer.transform(source, result);
        // Output to console for testing
        StreamResult consoleResult = new StreamResult(System.out);
        transformer.transform(source, consoleResult);

This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I've read the sentence from a file)

how to display progress while loading a url to webview in android?

You will have to over ride onPageStarted and onPageFinished callbacks

mWebView.setWebViewClient(new WebViewClient() {

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progressBar!= null && progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            return true;
        }

        public void onPageFinished(WebView view, String url) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            alertDialog.setTitle("Error");
            alertDialog.setMessage(description);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });

Use of ~ (tilde) in R programming Language

R defines a ~ (tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:

library(datasets)
lm( myFormula, data=iris)

help("~") or help("formula") will teach you more.

@Spacedman has covered the basics. Let's discuss how it works.

First, being an operator, note that it is essentially a shortcut to a function (with two arguments):

> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs

That can be helpful to know for use in e.g. apply family commands.

Second, you can manipulate the formula as text:

oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )

Third, you can manipulate it as a list:

myFormula[[2]]
myFormula[[3]]

Finally, there are some helpful tricks with formulae (see help("formula") for more):

myFormula <- Species ~ . 

For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.

How to call servlet through a JSP page

You can either post HTML form to URL, which is mapped to servlet or insert your data in HttpServletRequest object you pass to jsp page.

How to play YouTube video in my Android application?

I didn't want to have to have the YouTube app present on the device so I used this tutorial:

http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html

...to produce this code in my app:

WebView mWebView; 

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.video_webview);
    mWebView=(WebView)findViewById(R.id.videoview);

    //build your own src link with your video ID
    String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
        }
    });
    WebSettings ws = mWebView.getSettings();
    ws.setJavaScriptEnabled(true);
    mWebView.loadData(videoStr, "text/html", "utf-8");

}

//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:background="#000000"
    android:id="@+id/bmp_programme_ll"
    android:orientation="vertical" >

   <WebView
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />  
</LinearLayout>     

This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.

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

Step 1: Disconnect from your local account.

Step 2: Again Connect to Server with your admin user

Step 3: Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK

Step 4: Disconnect and connect to your local login and create database.

java.sql.SQLException: Exhausted Resultset

I've seen this error while trying to access a column value after processing the resultset.

if (rs != null) {
  while (rs.next()) {
    count = rs.getInt(1);
  }
  count = rs.getInt(1); //this will throw Exhausted resultset
}

Hope this will help you :)

How do I exclude Weekend days in a SQL Server query?

The answer depends on your server's week-start set up, so it's either

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)

if Sunday is the first day of the week for your server

or

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)

if Monday is the first day of the week for your server

Comment if you've got any questions :-)

Update cordova plugins in one command

Here's a bash script I use, works on OSX 10.11.3.

#!/bin/bash

PLUGINS=$(cordova plugin list | awk '{print $1}')

for PLUGIN in $PLUGINS; do
    cordova plugin rm $PLUGIN --save && cordova plugin add $PLUGIN --save
done

This may help if there are conflicts, per shan's comment. The difference is the addition of the --force flag when removing.

#!/bin/bash

PLUGINS=$(cordova plugin list | awk '{print $1}')

for PLUGIN in $PLUGINS; do
    cordova plugin rm $PLUGIN --force --save && cordova plugin add $PLUGIN --save
done

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Find and replace strings in vim on multiple lines

We don't need to bother entering the current line number.

If you would like to change each foo to bar for current line (.) and the two next lines (+2), simply do:

:.,+2s/foo/bar/g

If you want to confirm before changes are made, replace g with gc:

:.,+2s/foo/bar/gc

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

Footnotes for tables in LaTeX

A maybe not-so-elegant method, which I think is just a variation of what some other people have said, is to just hardcode it. Many journals have a template that in some way allows for table footnotes, so I try to keep things pretty basic. Although, there really are some incredible packages already out there, and I think this thread does a good job of pointing that out.

\documentclass{article}
\begin{document}
\begin{table}[!th]
\renewcommand{\arraystretch}{1.3} % adds row cushion
\caption{Data, level$^a$, and sources$^b$}
\vspace{4mm}
\centering
\begin{tabular}{|l|l|c|c|}
  \hline      
  \textbf{Data}  & \textbf{Description}   & \textbf{Level} & \textbf{Source} \\
  \hline      
  \hline
  Data1  &  Description. . . . . . . . . . . . . . . . . .   &  cnty & USGS \\
  \hline
  Data2  &  Description. . . . . . . . . . . . . . . . . .   &  MSA & USGS \\
  \hline
  Data3  &  Description. . . . . . . . . . . . . . . . . .   &  cnty & Census  \\
  \hline  
\end{tabular}
\end{table}
\footnotesize{$^a$ The smallest spatial unit is county, $^b$ more details in appendix A}\\
\end{document}

Output from above code

What is a segmentation fault?

Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don't find an error in your code, maybe a memtest could help you.

The solution in this case, change the RAM.

edit:

Here there is a reference: Segmentation fault by hardware

How could I create a function with a completion handler in Swift?

I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.

My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.

To create a function with a completion handler

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")

     finished()

}

to use the function

     override func viewDidLoad() {

          yourFunctionName {

          //do something here after running your function
           print("Tada!!!!")
          }

    }

Your output will be

Doing something

Tada!!!

Hope this helps!

window.location.reload with clear cache

reload() is supposed to accept an argument which tells it to do a hard reload, ie, ignoring the cache:

location.reload(true);

I can't vouch for its reliability, you may want to investigate this further.

Fit background image to div

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

Laravel Eloquent inner join with multiple conditions

You can see the following code to solved the problem

return $query->join('kg_shops', function($join)
{
    $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
    $join->where('kg_shops.active','=', 1);
});

Or another way to solved it

 return $query->join('kg_shops', function($join)
{
    $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
    $join->on('kg_shops.active','=', DB::raw('1'));
});

How to format a duration in java? (e.g format H:MM:SS)

I'm not sure that is you want, but check this Android helper class

import android.text.format.DateUtils

For example: DateUtils.formatElapsedTime()

Maven: Command to update repository after adding dependency to POM

If you want to only download dependencies without doing anything else, then it's:

mvn dependency:resolve

Or to download a single dependency:

mvn dependency:get -Dartifact=groupId:artifactId:version

If you need to download from a specific repository, you can specify that with -DrepoUrl=...

Which data type for latitude and longitude?

In PostGIS, for points with latitude and longitude there is geography datatype.

To add a column:

alter table your_table add column geog geography;

To insert data:

insert into your_table (geog) values ('SRID=4326;POINT(longitude latitude)');

4326 is Spatial Reference ID that says it's data in degrees longitude and latitude, same as in GPS. More about it: http://epsg.io/4326

Order is Longitude, Latitude - so if you plot it as the map, it is (x, y).

To find closest point you need first to create spatial index:

create index on your_table using gist (geog);

and then request, say, 5 closest to a given point:

select * 
from your_table 
order by geog <-> 'SRID=4326;POINT(lon lat)' 
limit 5;

Handling ExecuteScalar() when no results are returned

I used this in my vb code for the return value of a function:

If obj <> Nothing Then Return obj.ToString() Else Return "" End If

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1

How to change time in DateTime?

one liner

var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));

would bring back todays date with a time of 4:30:00, replace DateTime.Now with any date object

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

Getting Lat/Lng from Google marker

There are a lot of answers to this question, which never worked for me (including suggesting getPosition() which doesn't seem to be a method available for markers objects). The only method that worked for me in maps V3 is (simply) :

var lat = marker.lat();
var long = marker.lng();

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from: https://dev.mysql.com/downloads/connector/python/

Git says local branch is behind remote branch, but it's not

To diagnose it, follow this answer.

But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)

I tried git pull -s recursive -X ours but didnt work the way I wanted, it could be an option tho, but backup first!!!

Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...

How to hide Bootstrap modal with javascript?

I had better luck making the call after the "shown" callback occurred:

$('#myModal').on('shown', function () {
      $('#myModal').modal('hide');
})

This ensured the modal was done loading before the hide() call was made.

Quicksort: Choosing the pivot

Never ever choose a fixed pivot - this can be attacked to exploit your algorithm's worst case O(n2) runtime, which is just asking for trouble. Quicksort's worst case runtime occurs when partitioning results in one array of 1 element, and one array of n-1 elements. Suppose you choose the first element as your partition. If someone feeds an array to your algorithm that is in decreasing order, your first pivot will be the biggest, so everything else in the array will move to the left of it. Then when you recurse, the first element will be the biggest again, so once more you put everything to the left of it, and so on.

A better technique is the median-of-3 method, where you pick three elements at random, and choose the middle. You know that the element that you choose won't be the the first or the last, but also, by the central limit theorem, the distribution of the middle element will be normal, which means that you will tend towards the middle (and hence, nlog(n) time).

If you absolutely want to guarantee O(nlog(n)) runtime for the algorithm, the columns-of-5 method for finding the median of an array runs in O(n) time, which means that the recurrence equation for quicksort in the worst case will be:

T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)

By the Master Theorem, this is O(nlog(n)). However, the constant factor will be huge, and if worst case performance is your primary concern, use a merge sort instead, which is only a little bit slower than quicksort on average, and guarantees O(nlog(n)) time (and will be much faster than this lame median quicksort).

Explanation of the Median of Medians Algorithm

Best way to get hostname with php

You could also use...

$hostname = getenv('HTTP_HOST');

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

A quick-and-dirty approach:

function exec_sql_from_file($path, PDO $pdo) {
    if (! preg_match_all("/('(\\\\.|.)*?'|[^;])+/s", file_get_contents($path), $m))
        return;

    foreach ($m[0] as $sql) {
        if (strlen(trim($sql)))
            $pdo->exec($sql);
    }
}

Splits at reasonable SQL statement end points. There is no error checking, no injection protection. Understand your use before using it. Personally, I use it for seeding raw migration files for integration testing.

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

(WAMP/XAMP) send Mail using SMTP localhost

Method 1 (Preferred) - Using hMailServer


After installation, you need the following configuration to properly send mail from wampserver:

1) When you first open hMailServer Administrator, you need to add a new domain.
2) Click on the "Add Domain ..." button at the Welcome page. 
3) Under the domain text field, enter your computer's IP, in this case it should be 127.0.0.1.
4) Click on the Save button.
5) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
6) Enter "localhost" in the localhost name field.
7) Click on the Save button.

If you need to send mail using a FROM addressee of another computer, you need to allow deliveries from External to External accounts. To do that, follow these steps:

1) Go to Settings>Advanced>IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
2) Check the Allow Deliveries from External to External accounts checkbox.
3) Save settings using Save button.

(However, Windows Live/Hotmail has denied all emails coming from dynamic IPs, which most residential computers are using. The workaround is to use Gmail account )

Note to use Gmail users :

1) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
2) Enter "smtp.gmail.com" in the Remote Host name field.
3) Enter "465" as the port number
4) Check "Server requires authentication"
5) Enter gmail address in the Username
6) Enter gmail password in the password 
7) Check "Use SSL"

(Note, From field doesnt function with gmail)
*p.s. For some people it might also be needed to untick everything under require SMTP authentication in :

  • for local : Settings>Advanced>IP Ranges>"My Computer"
  • for external : Settings>Advanced>IP Ranges>"Internet"

Method 2 - Using SendMail

You can use SendMail installation.


Method 3 - Using different methods

Use any of these methods.

How return error message in spring mvc @Controller

As Sotirios Delimanolis already pointed out in the comments, there are two options:

Return ResponseEntity with error message

Change your method like this:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
                              @RequestHeader(value="Secret-key") String secretKey) {
    try {
        // see note 1
        return ResponseEntity
            .status(HttpStatus.CREATED)                 
            .body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
    }
    catch(ChekingCredentialsFailedException e) {
        e.printStackTrace(); // see note 2
        return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body("Error Message");
    }
}

Note 1: You don't have to use the ResponseEntity builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI).

Note 2: Don't use printStackTrace(), use a logger instead.

Provide an @ExceptionHandler

Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice like this:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(ChekingCredentialsFailedException.class)
    public ResponseEntity handleException(ChekingCredentialsFailedException e) {
        // log exception
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body("Error Message");
    }        
}

Note that methods which are annotated with @ExceptionHandler are allowed to have very flexible signatures. See the Javadoc for details.

Access multiple elements of list knowing their index

My answer does not use numpy or python collections.

One trivial way to find elements would be as follows:

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]

Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Using a Python subprocess call to invoke a Python script

First, check if somescript.py is executable and starts with something along the lines of #!/usr/bin/python. If this is done, then you can use subprocess.call('./somescript.py').

Or as another answer points out, you could do subprocess.call(['python', 'somescript.py']).

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

http://www2.research.att.com/~bs/C++0xFAQ.html#init-list

Volatile boolean vs AtomicBoolean

Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

Retrieve CPU usage and memory usage of a single process on Linux?

Launch a program and monitor it

This form is useful if you want to benchmark an executable easily:

topp() (
  $* &>/dev/null &
  pid="$!"
  trap ':' INT
  echo 'CPU  MEM'
  while sleep 1; do ps --no-headers -o '%cpu,%mem' -p "$pid"; done
  kill "$pid"
)
topp ./myprog arg1 arg2

Now when you hit Ctrl + C it exits the program and stops monitoring. Sample output:

CPU  MEM
20.0  1.3
35.0  1.3
40.0  1.3

Related: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

Tested on Ubuntu 16.04.

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

Redirect echo output in shell script to logfile

You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

How can one display images side by side in a GitHub README.md?

This will display the three images side by side if the images are not too wide.

<p float="left">
  <img src="/img1.png" width="100" />
  <img src="/img2.png" width="100" /> 
  <img src="/img3.png" width="100" />
</p>

Python-Requests close http connection

To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session

headers = {
'Host' : '1.2.3.4',
'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
'Accept' : '*/*',
'Accept-Encoding' : 'deflate, gzip',
'Accept-Language' : 'it_IT'
}

url = "https://stream.twitter.com/1/statuses/filter.json"
#r = requests.get(url, headers = headers) #this triggers keep-alive: True
s = requests.Session()
r = requests.Request('GET', url, headers)

How to use comparison and ' if not' in python?

Operator precedence in python
You can see that not X has higher precedence than and. Which means that the not only apply to the first part (u0 <= u). Write:

if not (u0 <= u and u < u0+step):  

or even

if not (u0 <= u < u0+step):  

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

You use RAISE_APPLICATION_ERROR in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.

For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:

ORA-00001: unique constraint (USERS.PK_USER_KEY) violated

Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.

raise_application_error(-20101, 'User ' || in_user || ' already exists!');

Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.

Note that user defined errors must be in the range between -20000 and -20999.

The following link provides lots of good information on this topic and Oracle exceptions in general.

Clearing NSUserDefaults

You can remove the application's persistent domain like this:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

In Swift 3 and later:

if let bundleID = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundleID)
}

This is similar to the answer by @samvermette but is a little bit cleaner IMO.

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

How to loop through elements of forms with JavaScript?

You can use getElementsByTagName function, it returns a HTMLCollection of elements with the given tag name.

var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
    if(elements[i].value == "") {
        alert('empty');
        //Do something here
    }
}

DEMO

You can also use document.myform.getElementsByTagName provided you have given a name to yoy form

DEMO with form Name

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
Out[45]: 
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar


### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Out[46]: 
name   
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64


### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
Out[48]: 
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

Visually managing MongoDB documents and collections

Here are some popular MongoDB GUI administration tools:

Open source

  • dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.

    dbKoda screenshot

  • Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.

  • adminMongo - web-based or Electron app. Supports server monitoring and document editing.

Closed source

  • NoSQLBoosterfull-featured shell-centric cross-platform GUI tool for MongoDB v2.2-4. Free, Personal, and Commercial editions (feature comparison matrix).
  • MongoDB Compass – provides a graphical user interface that allows you to visualize your schema and perform ad-hoc find queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update queries or access to the shell.
  • Studio 3T, formerly MongoChef – a multi-platform in-place data browser and editor desktop GUI for MongoDB (Core version is free for personal and non-commercial use). Last commit: 2017-Jul-24
  • Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04

  • HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.

  • Database Master – a Windows based MongoDB Management Studio, supports also RDBMS. (not free)
  • SlamData - an open source web-based user-interface that allows you to upload and download data, run queries, build charts, explore data.

Abandoned projects

  • RockMongo – a MongoDB administration tool, written in PHP5. Allegedly the best in the PHP world. Similar to PHPMyAdmin. Last version: 2015-Sept-19
  • Fang of Mongo – a web-based UI built with Django and jQuery. Last commit: 2012-Jan-26, in a forked project.
  • Opricot – a browser-based MongoDB shell written in PHP. Latest version: 2010-Sep-21
  • Futon4Mongo – a clone of the CouchDB Futon web interface for MongoDB. Last commit: 2010-Oct-09
  • MongoVUE – an elegant GUI desktop application for Windows. Free and non-free versions. Latest version: 2014-Jan-20
  • UMongo – a full-featured open-source MongoDB server administration tool for Linux, Windows, Mac; written in Java. Last commit 2014-June
  • Mongo3 – a Ruby/Sinatra-based interface for cluster management. Last commit: Apr 16, 2013

jQuery UI DatePicker - Change Date Format

dateFormat

The format for parsed and displayed dates. This attribute is one of the regionalisation attributes. For a full list of the possible formats see the formatDate function.

Code examples Initialize a datepicker with the dateFormat option specified.

$( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });

Get or set the dateFormat option, after init.

//getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );
//setter
$( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );

JSON string to JS object

Some modern browsers have support for parsing JSON into a native object:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.

Purge or recreate a Ruby on Rails database

To drop a particular database, you can do this on rails console:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

And then migrate DB again

$bundle exec rake db:migrate 

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

Conda command is not recognized on Windows 10

I had also faced the same problem just an hour back. I was trying to install QuTip Quantum Toolbox in Python Unfortunately, I didn't stumble onto this page in time. Say you have downloaded Anaconda installer and run it until the end. Naively, I opened the command prompt in windows 10 and proceded to type the following commands as given in the qutip installation docs.

conda create -n qutip-env

conda config --append channels conda-forge

conda install qutip

But as soon as I typed the first line I got the following response

conda is not recognized as an internal or external command, operable program or batch file

error messsage

I went ahead and tried some other things as seen in this figures error message Finally after going through a number conda websites, I understood how one fixes this problem. Type Anaconda prompt in the search bar at the bottom like this (same place where you hail Cortana) Anaconda prompt

Once you are here all the conda commands will work as usual

Eclipse add Tomcat 7 blank server name

I am running kepler in ubuntu and had the same problem getting eclipse to recognize the tomcat7 server. My path to install directory was fine and deleting/renaming the files only did not fix it either.

This is what worked for me:

run the following in terminal:

cd ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/    
rm org.eclipse.jst.server.tomcat.core.prefs    
rm org.eclipse.wst.server.core.prefs
cd /usr/share/tomcat7
sudo service tomcat7 stop
sudo update-rc.d tomcat7 disable
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo ln -s /var/log/tomcat7 log
sudo chmod -R 777 /usr/share/tomcat7/conf
sudo ln -s /var/lib/tomcat7/common common
sudo ln -s /var/lib/tomcat7/server server
sudo ln -s /var/lib/tomcat7/shared shared

restart eclipse, delete tomcat7 server. Re-add server and everything then worked.

Here is the link I used. http://linux.mjnet.eu/post/1319/tomcat-7-ubuntu-13-04-and-eclipse-kepler-problem-to-run/

How can I resize an image using Java?

Simply use Burkhard's answer but add this line after creating the graphics:

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

You could also set the value to BICUBIC, it will produce a better quality image but is a more expensive operation. There are other rendering hints you can set but I have found that interpolation produces the most notable effect. Keep in mind if you want to zoom in in a lot, java code most likely will be very slow. I find larger images start to produce lag around 300% zoom even with all rendering hints set to optimize for speed over quality.

How do I implement IEnumerable<T>

If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.

List<MyObject> myList = new List<MyObject>();

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

How to get GET (query string) variables in Express.js on Node.js?

In Express it's already done for you and you can simply use req.query for that:

var id = req.query.id; // $_GET["id"]

Otherwise, in NodeJS, you can access req.url and the builtin url module to url.parse it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

Self Join to get employee manager name

SELECT e1.empno EmployeeId, e1.ename EmployeeName, 
       e1.mgr ManagerId, e2.ename AS ManagerName
FROM   emp e1, emp e2
       where e1.mgr = e2.empno

Show/Hide Table Rows using Javascript classes

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.

Here's the fiddle: link.

What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".

I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.

$(".toggler").click(function(e){
    // you handle the event here
});

With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)

In the event handler, I do this:

$('.cat'+$(this).attr('data-prod-cat')).toggle();

With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).

I hope this was explanatory enough.

Tensorflow import error: No module named 'tensorflow'

In Windows 64, if you did this sequence correctly:

Anaconda prompt:

conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:

conda install spyder

This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.

Always prefer to install these libraries with "conda install" instead of "pip".

Is there a kind of Firebug or JavaScript console debug for Android?

I sometimes print debugging output to the browser window. Using jQuery, you could send output messages to a display area on your page:

<div id='display'></div>

$('#display').text('array length: ' + myArray.length);

Or if you want to watch JavaScript variables without adding a display area to your page:

function debug(txt) {
    $('body').append("<div style='width:300px;background:orange;padding:3px;font-size:13px'>" + txt + "</div>");
}

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

accessing a variable from another class

I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.

Source: Bad experiences. Good lessons.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How to calculate percentage with a SQL statement

I simply use this when ever I need to work out a percentage..

ROUND(CAST((Numerator * 100.0 / Denominator) AS FLOAT), 2) AS Percentage

Note that 100.0 returns decimals, whereas 100 on it's own will round up the result to the nearest whole number, even with the ROUND() function!

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

Simple two column html layout without using tables

Well, you can do css tables instead of html tables. This keeps your html semantically correct, but allows you to use tables for layout purposes.

This seems to make more sense than using float hacks.

<html>
  <head>
    <style>

#content-wrapper{
  display:table;
}

#content{
  display:table-row;
}

#content>div{
  display:table-cell
}

/*adding some extras for demo purposes*/
#content-wrapper{
  width:100%;
  height:100%;
  top:0px;
  left:0px;
  position:absolute;
}
#nav{
  width:100px;
  background:yellow;
}
#body{
  background:blue;
}
</style>

  </head>
  <body>
    <div id="content-wrapper">
      <div id="content">
        <div id="nav">
          Left hand content
        </div>
        <div id="body">
          Right hand content
        </div>
      </div>
    </div>
  </body>
</html>

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Unable to Install Any Package in Visual Studio 2015

In my case, This problem was caused by a mismatch in my Target framework setting under each project. When I created a new project, VS 2015 defaulted to 4.5.2, however all my nuget packages were built for 4.6.

For some reason, VS 2015 was not showing me these errors. I didn't see them until I created a new empty project and tried to add my nuget project there. This behavior may have been aggravated because I had renamed the project a few times during the initial setup.

I solved the problem by

  • changing the Target Framework on my projects to 4.6
  • closed VS 2015
  • deleted "packages", "obj" and "bin" folders
  • re-open the solution and try to add the nuget package again.