Programs & Examples On #Live streaming

Live Streaming is the action of streaming a media (voice, video) over the network in real time.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Solved the problem by upgrading the dependency to below version

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

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

Live-stream video from one android phone to another over WiFi

If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.

If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).

Quick sample code for the server:

// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();

On the player side it is a bit tricky, you could try this:

// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();

Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.

See also:

Stream live video from phone to phone using socket fd

MediaPlayer stutters at start of mp3 playback

What is the difference between RTP or RTSP in a streaming server?

You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.

You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...

So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.

Read the documents I linked here, they are a good starting point.

Documentation for using JavaScript code inside a PDF file

Probably you are looking for JavaScript™ for Acrobat® API Reference.

This reference should be the most complete. But, as @Orbling said, not all PDF viewers might support all of the API.

EDIT:

It turns out there are newer versions of the reference in Acrobat SDK (thanks to @jss).

Acrobat Developer Center contains links to different versions of documentation. Current version of JavaScript reference from Acrobat DC SDK is available there too.

jQuery selector first td of each row

You can do it like this

_x000D_
_x000D_
$(function(){_x000D_
  $("tr").find("td:eq(0)").css("color","red");_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col_1</td>_x000D_
    <td>col_2</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

How to convert a PIL Image into a numpy array?

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

You can transform the image into numpy by parsing the image into numpy() function after squishing out the features( unnormalization)

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

How to uninstall a package installed with pip install --user

Be careful though, for those who using pip install --user some_pkg inside a virtual environment.

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

In this case, you have to deactivate the current virtual environment, then use the corresponding python/pip executable to list or uninstall the user site packages:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

Note that this issue was reported few years ago. And it seems that the current conclusion is: --user is not valid inside a virtual env's pip, since a user location doesn't really make sense for a virtual environment.

PHP is_numeric or preg_match 0-9 validation

If you're only checking if it's a number, is_numeric() is much much better here. It's more readable and a bit quicker than regex.

The issue with your regex here is that it won't allow decimal values, so essentially you've just written is_int() in regex. Regular expressions should only be used when there is a non-standard data format in your input; PHP has plenty of built in validation functions, even an email validator without regex.

No module named pkg_resources

A lot of answers are recommending the following but if you read through the source of that script, you'll realise it's deprecated.

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

If your pip is also broken, this won't work either.

pip install setuptools

I found I had to run the command from Ensure pip, setuptools, and wheel are up to date, to get pip working again.

python -m pip install --upgrade pip setuptools wheel

What is the meaning of "operator bool() const"

Another common use is for std containers to do equality comparison on key values inside custom objects

class Foo
{
    public: int val;
};

class Comparer { public:
bool operator () (Foo& a, Foo&b) const {
return a.val == b.val; 
};

class Blah
{
std::set< Foo, Comparer > _mySet;
};

Difference between Mutable objects and Immutable objects

They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.

What should I set JAVA_HOME environment variable on macOS X 10.6?

For Fish Shell users, use something like the following: alias java7 "set -gx JAVA_HOME (/usr/libexec/java_home -v1.7)"

Run as java application option disabled in eclipse

Had the same problem. I apparently wrote the Main wrong:

public static void main(String[] args){

I missed the [] and that was the whole problem.

Check and recheck the Main function!

Get the IP address of the machine

I do not think there is a definitive right answer to your question. Instead there is a big bundle of ways how to get close to what you wish. Hence I will provide some hints how to get it done.

If a machine has more than 2 interfaces (lo counts as one) you will have problems to autodetect the right interface easily. Here are some recipes on how to do it.

The problem, for example, is if hosts are in a DMZ behind a NAT firewall which changes the public IP into some private IP and forwards the requests. Your machine may have 10 interfaces, but only one corresponds to the public one.

Even autodetection does not work in case you are on double-NAT, where your firewall even translates the source-IP into something completely different. So you cannot even be sure, that the default route leads to your interface with a public interface.

Detect it via the default route

This is my recommended way to autodetect things

Something like ip r get 1.1.1.1 usually tells you the interface which has the default route.

If you want to recreate this in your favourite scripting/programming language, use strace ip r get 1.1.1.1 and follow the yellow brick road.

Set it with /etc/hosts

This is my recommendation if you want to stay in control

You can create an entry in /etc/hosts like

80.190.1.3 publicinterfaceip

Then you can use this alias publicinterfaceip to refer to your public interface.

Sadly haproxy does not grok this trick with IPv6

Use the environment

This is a good workaround for /etc/hosts in case you are not root

Same as /etc/hosts. but use the environment for this. You can try /etc/profile or ~/.profile for this.

Hence if your program needs a variable MYPUBLICIP then you can include code like (this is C, feel free to create C++ from it):

#define MYPUBLICIPENVVAR "MYPUBLICIP"

const char *mypublicip = getenv(MYPUBLICIPENVVAR);

if (!mypublicip) { fprintf(stderr, "please set environment variable %s\n", MYPUBLICIPENVVAR); exit(3); }

So you can call your script/program /path/to/your/script like this

MYPUBLICIP=80.190.1.3 /path/to/your/script

this even works in crontab.

Enumerate all interfaces and eliminate those you do not want

The desperate way if you cannot use ip

If you do know what you do not want, you can enumerate all interfaces and ignore all the false ones.

Here already seems to be an answer https://stackoverflow.com/a/265978/490291 for this approach.

Do it like DLNA

The way of the drunken man who tries to drown himself in alcohol

You can try to enumerate all the UPnP gateways on your network and this way find out a proper route for some "external" thing. This even might be on a route where your default route does not point to.

For more on this perhaps see https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol

This gives you a good impression which one is your real public interface, even if your default route points elsewhere.

There are even more

Where the mountain meets the prophet

IPv6 routers advertise themselves to give you the right IPv6 prefix. Looking at the prefix gives you a hint about if it has some internal IP or a global one.

You can listen for IGMP or IBGP frames to find out some suitable gateway.

There are less than 2^32 IP addresses. Hence it does not take long on a LAN to just ping them all. This gives you a statistical hint on where the majority of the Internet is located from your point of view. However you should be a bit more sensible than the famous https://de.wikipedia.org/wiki/SQL_Slammer

ICMP and even ARP are good sources for network sideband information. It might help you out as well.

You can use Ethernet Broadcast address to contact to all your network infrastructure devices which often will help out, like DHCP (even DHCPv6) and so on.

This additional list is probably endless and always incomplete, because every manufacturer of network devices is busily inventing new security holes on how to auto-detect their own devices. Which often helps a lot on how to detect some public interface where there shouln't be one.

'Nuff said. Out.

How do I set a cookie on HttpClient's HttpRequestMessage

For me the simple solution works to set cookies in HttpRequestMessage object.

protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
    requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");

    return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}

How to delete a folder in C++?

This works for deleting all the directories and files within a directory.

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
    cout << "Enter the DirectoryName to Delete : ";
    string directoryName;
    cin >> directoryName;
    string a = "rmdir /s /q " + directoryName;
    system(a.c_str());
    return 0;
}

How to detect browser using angularjs?

I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.

angular.module('myModule').service('browserDetectionService', function() {

 return {
isCompatible: function () {

  var browserInfo = navigator.userAgent;
  var browserFlags =  {};

  browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
  browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
  browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
  browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
  browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;

  browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
  browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
  browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
  browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
  browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
  browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
  browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here

  browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
  browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
  browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;

  return !browserFlags.ISOLD;
  }
};

});

How to change color of Toolbar back button in Android?

To style the Toolbar on Android 21+ it's a bit different.

<style name="DarkTheme.v21" parent="DarkTheme.v19">
        <!-- toolbar background color -->
        <item name="android:navigationBarColor">@color/color_primary_blue_dark</item>
        <!-- toolbar back button color -->
        <item name="toolbarNavigationButtonStyle">@style/Toolbar.Button.Navigation.Tinted</item>
    </style>

    <style name="Toolbar.Button.Navigation.Tinted" parent="Widget.AppCompat.Toolbar.Button.Navigation">
        <item name="tint">@color/color_white</item>
    </style>

jquery save json data object in cookie

With serialize the data as JSON and Base64, dependency jquery.cookie.js :

var putCookieObj = function(key, value) {
    $.cookie(key, btoa(JSON.stringify(value)));
}

var getCookieObj = function (key) {
    var cookie = $.cookie(key);
    if (typeof cookie === "undefined") return null;
    return JSON.parse(atob(cookie));
}

:)

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

Couldn't connect to server 127.0.0.1:27017

I followed the doc at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat/.

After configured and reboot, I executed sudo service mongod start and got ... [FAILED].

At last, I found that mongod had started. I think the yum install added it to auto start.

To check if your mongod is running: service mongod status .

Hope this can help someone has same problem.

How to view UTF-8 Characters in VIM or Gvim

On Microsoft Windows, gvim wouldn't allow you to select non-monospaced fonts. Unfortunately Latha is a non-monospaced font.

There is a hack way to make it happen: Using FontForge (you can download Windows binary from http://www.geocities.jp/meir000/fontforge/) to edit the Latha.ttf and mark it as a monospaced font. Doing like this:

  1. Load fontforge, select latha.ttf.
  2. Menu: Element -> Font Info
  3. Select "OS/2" from left-hand list on Font Info dialog
  4. Select "Panose" tab
  5. Set Proportion = Monospaced
  6. Save new TTF version of this font, try it out!

Good luck!

Finding element's position relative to the document

You can get top and left without traversing DOM like this:

function getCoords(elem) { // crossbrowser version
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

    var clientTop = docEl.clientTop || body.clientTop || 0;
    var clientLeft = docEl.clientLeft || body.clientLeft || 0;

    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
}

How to get DropDownList SelectedValue in Controller in MVC

Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.

new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}

List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });

@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)

You can also do something like this for a database driven select list. you will need to set selected in your controller

@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")

Something like this but better solutions exist this is just one method.

foreach (CountryModel item in CountryModel.GetCountryList())
    {
        if (item.CountryPhoneCode.Trim() != "974")
        {
            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

        }
        else {


            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

        }
    }

How to scroll to top of long ScrollView layout?

Very easy

    ScrollView scroll = (ScrollView) findViewById(R.id.addresses_scroll);
    scroll.setFocusableInTouchMode(true);
    scroll.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);

OpenCV & Python - Image too big to display

Try this:

image = cv2.imread("img/Demo.jpg")
image = cv2.resize(image,(240,240))

The image is now resized. Displaying it will render in 240x240.

AngularJS does not send hidden field value

Below Code will work for this IFF it in the same order as its mentionened make sure you order is type then name, ng-model ng-init, value. thats It.

How to get sp_executesql result into a variable?

Declare @variable int
Exec @variable = proc_name

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

pycharm running way slow

I found a solution to this problem that works beautifully on Windows, and wanted to share it.

Solutions that didn't work: I have 16GB of RAM and was still having horrible lag. PyCharm takes less than 1GB of RAM for me, so that wasn't the issue. Turning off inspections didn't help at all, and I didn't have any special plugins that I recall. I also tried playing around with CPU affinities for the process, which briefly worked but not really.

What worked beautifully, almost perfectly:

  1. Set PyCharm's CPU priority to Above Normal
  2. Set the CPU priority for Python processes to Below Normal

You can do this manually, but I recommend using a program which will preserve the setting across restarts and for multiple instances. I used Process Hacker: Right click on the process -> Priority -> Set the priority. Then right click again -> Process -> and select "Save for pycharm64.exe" and similarly for python "Save for python.exe." Finally in Process Hacker go to Options and select "Start when I log on." This will make it so that ALL Pycharm and python executables acquire these CPU priorities, even after restarting the program and/or Windows, and no matter how many python instances you launch.

Basically, much of the PyCharm's lag may be due to conflict with other programs. Think about it: Yes PyCharm requires a lot of CPU, but the PyCharm developers aren't stupid. They have probably at least ensured it can run without lag on an empty core. But now you open Chrome and 30 tabs, Fiddler, an FTP program, iTunes, Word, Slack, etc, and they all compete with PyCharm at the same CPU priority level. Whenever the sum of all programs > 100% on a core, you see lag. Switching to Above Normal priority gives PyCharm something closer to the empty core that it was probably tested on.

As for Below Normal on python.exe, basically you don't want to slow your computer down with your own development. Most python programs are essentially "batch" programs, and you probably won't notice the extra time it takes to run. I don't recommend this if you are developing a graphical interactive program.

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

How to change the Title of the window in Qt?

void    QWidget::setWindowTitle ( const QString & )

EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.

VBA Excel Provide current Date in Text box

The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.

From VBA you might try using:

textbox.Value = Format(Date(),"mm/dd/yy")

Do I cast the result of malloc?

Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To even do better boolean mapping to Y/N, add to your hibernate configuration:

<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>

Now you can use booleans in HQL, for example:

"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"

The split() method in Java does not work on a dot (.)

The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\."). You need a double backslash, the second one escapes the first.

Split long commands in multiple lines through Windows batch file

The rule for the caret is:

A caret at the line end, appends the next line, the first character of the appended line will be escaped.

You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).

echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*

echo Test2
echo one & echo two
--- Output ---
Test2
one
two

echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two

echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two

To suppress the escaping of the next character you can use a redirection.

The redirection has to be just before the caret. But there exist one curiosity with redirection before the caret.

If you place a token at the caret the token is removed.

echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two


echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two

And it is also possible to embed line feeds into the string:

setlocal EnableDelayedExpansion
set text=This creates ^

a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed

The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.

It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).

What to do on TransactionTooLargeException

I faced with the same issue when I tried to send bitmap via Intent and at the same time when it happens I folded the application.

How it described in this article enter link description here it happens when an Activity is in the process of stopping, that means that the Activity was trying to send its saved state Bundles to the system OS for safe keeping for restoration later (after a config change or process death) but that one or more of the Bundles it sent were too large.

I solved it via hack by overriding onSaveInstanceState in my Activity:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // super.onSaveInstanceState(outState);
}

and comment call super. It is a dirty hack but it is working perfectly. Bitmap was successfully sent without crashes. Hope this will help someone.

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

Lombok is not generating getter and setter

When starting with a fresh eclipse installation you, in fact, need to "install" Lombok before being able to use it.

  1. Go where you Lombok jar is (e.g. (e.g. you can find in ~/.m2/repository/org/projectlombok/lombok/1.16.10/lombok-1.16.10.jar), run it (Example: java -jar lombok-1.16.10.jar). A window should appear, browse to your eclipse.exe location.
  2. Click on install.
  3. Launch Eclipse, update project configuration on all projects and voila.

dropping infinite values from dataframes in pandas?

The simplest way would be to first replace infs to NaN:

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

and then use the dropna:

df.replace([np.inf, -np.inf], np.nan).dropna(subset=["col1", "col2"], how="all")

For example:

In [11]: df = pd.DataFrame([1, 2, np.inf, -np.inf])

In [12]: df.replace([np.inf, -np.inf], np.nan)
Out[12]:
    0
0   1
1   2
2 NaN
3 NaN

The same method would work for a Series.

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

PHP absolute path to root

Create a constant with absolute path to the root by using define in ShowInfo.php:

define('ROOTPATH', __DIR__);

Or PHP <= 5.3

define('ROOTPATH', dirname(__FILE__));

Now use it:

if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
  // ...
}

Or use the DOCUMENT_ROOT defined in $_SERVER:

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
  // ...
}

Laravel Eloquent ORM Transactions

You can do this:

DB::transaction(function() {
      //
});

Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.

Using CMake to generate Visual Studio C++ project files

Not sure if it's directly related to the question, but I was looking for an answer for how to generate *.sln from cmake projects I've discovered that one can use something like this:

cmake -G "Visual Studio 10"

The example generates needed VS 2010 files from an input CMakeLists.txt file

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

In package.json change the "start" value as follows

Note: Run $sudo npm start, You need to use sudo to run react scripts on port 80

enter image description here

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

How can I flush GPU memory using CUDA (physical reset is unavailable)

for the ones using python:

import torch, gc
gc.collect()
torch.cuda.empty_cache()

Bootstrap carousel resizing image

The reason why your image is resizing which is because it is fluid. You have two ways to do it:

  1. Either give a fixed dimension to your image using CSS like:

    .carousel-inner > .item > img {
      width:640px;
      height:360px;
    }
  2. A second way to can do this:

    .carousel {
      width:640px;
      height:360px;
    }

How to calculate percentage with a SQL statement

The following should work

ID - Key
Grade - A,B,C,D...

EDIT: Moved the * 100 and added the 1.0 to ensure that it doesn't do integer division

Select 
   Grade, Count(ID) * 100.0 / ((Select Count(ID) From MyTable) * 1.0)
From MyTable
Group By Grade

jQuery How to Get Element's Margin and Padding?

Edit:

use jquery plugin: jquery.sizes.js

$('img').margin() or $('img').padding()

return:

{bottom: 10 ,left: 4 ,top: 0 ,right: 5}

get value:

$('img').margin().top

Python: How to get stdout after running os.system?

import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

Merging dictionaries in C#

This doesn't explode if there are multiple keys ("righter" keys replace "lefter" keys), can merge a number of dictionaries (if desired) and preserves the type (with the restriction that it requires a meaningful default public constructor):

public static class DictionaryExtensions
{
    // Works in C#3/VS2008:
    // Returns a new dictionary of this ... others merged leftward.
    // Keeps the type of 'this', which must be default-instantiable.
    // Example: 
    //   result = map.MergeLeft(other1, other2, ...)
    public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others)
        where T : IDictionary<K,V>, new()
    {
        T newMap = new T();
        foreach (IDictionary<K,V> src in
            (new List<IDictionary<K,V>> { me }).Concat(others)) {
            // ^-- echk. Not quite there type-system.
            foreach (KeyValuePair<K,V> p in src) {
                newMap[p.Key] = p.Value;
            }
        }
        return newMap;
    }

}

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

Does Arduino use C or C++?

Arduino doesn't run either C or C++. It runs machine code compiled from either C, C++ or any other language that has a compiler for the Arduino instruction set.

C being a subset of C++, if Arduino can "run" C++ then it can "run" C.

If you don't already know C nor C++, you should probably start with C, just to get used to the whole "pointer" thing. You'll lose all the object inheritance capabilities though.

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

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

I encountered the same problem whilst trying to get Shinken 2.0.3 to fire up on Ubuntu. Eventually I did a full uninstall then reinstalled Shinken with pip -v. As it cleaned up, it mentioned:

Warning: missing python-pycurl lib, you MUST install it before launch the shinken daemons

Installed that with apt-get, and all the brokers fired up as expected :-)

How to fix corrupted git repository?

In my case, I was creating the repository from source code already in my pc and that error appeared. I deleted the .git folder and did everything again and it worked :)

Deleting queues in RabbitMQ

You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.

You need to use queue.delete now in order to delete it.

See the API documentation for details:

If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.

You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.

Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.

How to go to a specific element on page?

here is a simple javascript for that

call this when you need to scroll the screen to an element which has id="yourSpecificElementId"

window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));

and you need this function for the working:

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return [curtop];
    }
}

the screen will be scrolled to your specific element.

react-router go back a page how do you configure history?

This is a working BackButton component (React 0.14):

var React = require('react');
var Router = require('react-router');

var History = Router.History;

var BackButton = React.createClass({
  mixins: [ History ],
  render: function() {
    return (
      <button className="back" onClick={this.history.goBack}>{this.props.children}</button>
    );
  }
});

module.exports = BackButton;

You can off course do something like this if there is no history:

<button className="back" onClick={goBack}>{this.props.children}</button>

function goBack(e) {
  if (/* no history */) {
    e.preventDefault();
  } else {
    this.history.goBack();
  }
}

Reading file input from a multipart/form-data POST

Another way would be to use .Net parser for HttpRequest. To do that you need to use a bit of reflection and simple class for WorkerRequest.

First create class that derives from HttpWorkerRequest (for simplicity you can use SimpleWorkerRequest):

public class MyWorkerRequest : SimpleWorkerRequest
{
    private readonly string _size;
    private readonly Stream _data;
    private string _contentType;

    public MyWorkerRequest(Stream data, string size, string contentType)
        : base("/app", @"c:\", "aa", "", null)
    {
        _size = size ?? data.Length.ToString(CultureInfo.InvariantCulture);
        _data = data;
        _contentType = contentType;
    }

    public override string GetKnownRequestHeader(int index)
    {
        switch (index)
        {
            case (int)HttpRequestHeader.ContentLength:
                return _size;
            case (int)HttpRequestHeader.ContentType:
                return _contentType;
        }
        return base.GetKnownRequestHeader(index);
    }

    public override int ReadEntityBody(byte[] buffer, int offset, int size)
    {
        return _data.Read(buffer, offset, size);
    }

    public override int ReadEntityBody(byte[] buffer, int size)
    {
        return ReadEntityBody(buffer, 0, size);
    }
}

Then wherever you have you message stream create and instance of this class. I'm doing it like that in WCF Service:

[WebInvoke(Method = "POST",
               ResponseFormat = WebMessageFormat.Json,
               BodyStyle = WebMessageBodyStyle.Bare)]
    public string Upload(Stream data)
    {
        HttpWorkerRequest workerRequest =
            new MyWorkerRequest(data,
                                WebOperationContext.Current.IncomingRequest.ContentLength.
                                    ToString(CultureInfo.InvariantCulture),
                                WebOperationContext.Current.IncomingRequest.ContentType
                );

And then create HttpRequest using activator and non public constructor

var r = (HttpRequest)Activator.CreateInstance(
            typeof(HttpRequest),
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            new object[]
                {
                    workerRequest,
                    new HttpContext(workerRequest)
                },
            null);

var runtimeField = typeof (HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
if (runtimeField == null)
{
    return;
}

var runtime = (HttpRuntime) runtimeField.GetValue(null);
if (runtime == null)
{
    return;
}

var codeGenDirField = typeof(HttpRuntime).GetField("_codegenDir", BindingFlags.Instance | BindingFlags.NonPublic);
if (codeGenDirField == null)
{
    return;
}

codeGenDirField.SetValue(runtime, @"C:\MultipartTemp");

After that in r.Files you will have files from your stream.

Is it possible to use Java 8 for Android development?

A subset of Java 8 is supported now on Android Studio. Just make the Source and Target Compatibility adjustments from the window below:

File --> Project Structure

Adjustment Window

More information is given in the below link.

https://developer.android.com/studio/write/java8-support.html

Difference between java.lang.RuntimeException and java.lang.Exception

From oracle documentation:

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...

The source was not found, but some or all event logs could not be searched

If you are performing a new install of the SenseNet TaskManagement website on IIS (from source code, not WebPI), you will get this message, usually related to SignalR communication. As @nicole-caliniou points out, it is due to a key search in the Registry that fails.

To solve this for SenseNet TaskManagement v1.1.0, first find the registry key name in the web.config file. By default it is "SnTaskWeb".

 <appSettings>
   <add key="LogSourceName" value="SnTaskWeb" />

Open the registry editor, regedit.exe, and navigate to HKLM\SYSTEM\CurrentControlSet\Services\EventLog\SnTask. Right-click on SnTask and select New Key, and name the key SnTaskWeb for the configuration shown above. Then right-click on the SnTaskWeb element and select New Expandable String Value. The name should be EventMessageFile and the value data should be C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll.

Keywords: signalr, sensenet, regedit, permissions

How to delete a remote tag?

As @CubanX suggested, I've split this answer from my original:

Here is a method which is several times faster than xargs and may scale much more with tweaking. It uses the Github API, a personal access token, and leverages the utility parallel.

git tag | sorting_processing_etc | parallel --jobs 2 curl -i -X DELETE \ 
https://api.github.com/repos/My_Account/my_repo/git/refs/tags/{} -H 
\"authorization: token GIT_OAUTH_OR_PERSONAL_KEY_HERE\"  \
-H \"cache-control: no-cache\"`

parallel has many operating modes, but generally parallelizes any command you give it while allowing you to set limits on the number of processes. You can alter the --jobs 2 parameter to allow faster operation, but I had problems with Github's rate limits, which are currently 5000/hr, but also seems to have an undocumented short-term limit as well.


After this, you'll probably want to delete your local tags too. This is much faster so we can go back to using xargs and git tag -d, which is sufficient.

git tag | sorting_processing_etc | xargs -L 1 git tag -d

How do I run a simple bit of code in a new thread?

The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.

System.Threading.ThreadPool.QueueUserWorkItem(delegate {
    DoSomethingThatDoesntInvolveAControl();
}, null);

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

How can I debug a Perl script?

To run your script under the Perl debugger you should use the -d switch:

perl -d script.pl

But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want

So to use different debuggers you may do:

perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl

Look these modules here and here.

There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover

And many others.

How to Check if value exists in a MySQL database

SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'

Git Push Error: insufficient permission for adding an object to repository database

For Ubuntu (or any Linux)

From project root,

cd .git/objects
ls -al
sudo chown -R yourname:yourgroup *

You can tell what yourname and yourgroup should be by looking at the permissions on the majority of the output from that ls -al command

Note: remember the star at the end of the sudo line

How does a Linux/Unix Bash script know its own PID?

If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

sleep 1 &
mypid=$(ps -o ppid= -p "$!")

Tracking CPU and Memory usage per process

There was a requirement to get status and cpu / memory usage of some specific windows servers. I used below script:

This is an example of Windows Search Service.

  $cpu = Get-WmiObject win32_processor
  $search = get-service "WSearch"
  if ($search.Status -eq 'Running')
  {
  $searchmem = Get-WmiObject Win32_Service -Filter "Name = 'WSearch'"
  $searchid = $searchmem.ProcessID
  $searchcpu1 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
  Start-Sleep -Seconds 1
  $searchcpu2 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
  $searchp2p1 = $searchcpu2.PercentProcessorTime - $searchcpu1.PercentProcessorTime
  $searcht2t1 = $searchcpu2.Timestamp_Sys100NS - $searchcpu1.Timestamp_Sys100NS
  $searchcpu = [Math]::Round(($searchp2p1 / $searcht2t1 * 100) /$cpu.NumberOfLogicalProcessors, 1)
  $searchmem = [Math]::Round($searchcpu1.WorkingSetPrivate / 1mb,1)
  Write-Host 'Service is' $search.Status', Memory consumed: '$searchmem' MB, CPU Usage: '$searchcpu' %'
  }

  else
  {
  Write-Host Service is $search.Status -BackgroundColor Red
  }

How to disable logging on the standard error stream in Python?

Found an elegant solution using decorators, which addresses the following problem: what if you are writing a module with several functions, each of them with several debugging messages, and you want to disable logging in all functions but the one you are currently focusing on?

You can do it using decorators:

import logging, sys
logger = logging.getLogger()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)


def disable_debug_messages(func):
    def wrapper(*args, **kwargs):
        prev_state = logger.disabled
        logger.disabled = True
        result = func(*args, **kwargs)
        logger.disabled = prev_state
        return result
    return wrapper

Then, you can do:

@disable_debug_messages
def function_already_debugged():
    ...
    logger.debug("This message won't be showed because of the decorator")
    ...

def function_being_focused():
    ...
    logger.debug("This message will be showed")
    ...

Even if you call function_already_debugged from within function_being_focused, debug messages from function_already_debugged won't be showed. This ensures you will see only the debug messages from the function you are focusing on.

Hope it helps!

Adding a stylesheet to asp.net (using Visual Studio 2010)

Several things here.

First off, you're defining your CSS in 3 places!

In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.

I suggest you update your code in your ASP form from

<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;" 
        class="style6">

to this:

<td  class="style6">

And then update your css too

.style6
    {
        height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
    }

This removes the inline.

Now, to move it from the head of the webForm.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
    <link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
    <tr>
        <td class="style6">
            <asp:Menu ID="Menu1" runat="server">
                <Items>
                    <asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
                    <asp:MenuItem Text="About" Value="About"></asp:MenuItem>
                    <asp:MenuItem Text="Compliance" Value="Compliance">
                        <asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
                        <asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
                    </asp:MenuItem>
                    <asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
                    <asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
                </Items>
            </asp:Menu>
        </td>
    </tr>
    <tr>
        <td class="style6">
            <img alt="South University'" class="style7" 
                src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
    </tr>
    <tr>
        <td class="style2">
            <table class="style3">
                <tr>
                    <td>
                        &nbsp;</td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td style="color: #FFFFFF; background-color: #A3A3A3">
            This is the footer.</td>
    </tr>
</table>
</form>
</body>
</html>

Now, in a new file called master.css (in your css folder) add

ul {
list-style-type:none;
margin:0;
padding:0;
}

li {
display:inline;
padding:20px;
}
.style1
{
    width: 100%;
}
.style2
{
    height: 459px;
}
.style3
{
    width: 100%;
    height: 100%;
}
.style6
{
    height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
    width: 345px;
    height: 73px;
}

Best way to remove from NSMutableArray while iterating?

Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes.

Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.

under Xcode 6 this works

NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];

    for (id object in array)
    {
        if ( [object isNotEqualTo:@"whatever"]) {
           [itemsToKeep addObject:object ];
        }
    }
    array = nil;
    array = [[NSMutableArray alloc]initWithArray:itemsToKeep];

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Laravel password validation rule

This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:

    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }

Would output:

    [
        'The email must be a valid email address.',
        'The password must be at least 10 characters.',
        'The password format is invalid.',
    ]

(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)

use current date as default value for a column

You can use:

Insert into Event(Description,Date) values('teste', GETDATE());

Also, you can change your table so that 'Date' has a default, "GETDATE()"

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

ENOENT, no such file or directory

Specifically, rm yarn.lock and then yarn install fixed this for me.

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

Can I use CASE statement in a JOIN condition?

Yes, you can. Here is an example.

SELECT a.*
FROM TableA a
LEFT OUTER JOIN TableB j1 ON  (CASE WHEN LEN(COALESCE(a.NoBatiment, '')) = 3 
                                THEN RTRIM(a.NoBatiment) + '0' 
                                ELSE a.NoBatiment END ) = j1.ColumnName 

Why is document.write considered a "bad practice"?

I think the biggest problem is that any elements written via document.write are added to the end of the page's elements. That's rarely the desired effect with modern page layouts and AJAX. (you have to keep in mind that the elements in the DOM are temporal, and when the script runs may affect its behavior).

It's much better to set a placeholder element on the page, and then manipulate it's innerHTML.

How can I open a link in a new window?

This is not a very nice fix but it works:

CSS:

.new-tab-opener
{
    display: none;
}

HTML:

<a data-href="http://www.google.com/" href="javascript:">Click here</a>
<form class="new-tab-opener" method="get" target="_blank"></form>

Javascript:

$('a').on('click', function (e) {    
    var f = $('.new-tab-opener');
    f.attr('action', $(this).attr('data-href'));
    f.submit();
});

Live example: http://jsfiddle.net/7eRLb/

PHP calculate age

You can use the Carbon library, which is an API extension for DateTime.

You can:

function calculate_age($date) {
    $date = new \Carbon\Carbon($date);
    return (int) $date->diffInYears();
}

or:

$age = (new \Carbon\Carbon($date))->age;

Eclipse interface icons very small on high resolution screen in Windows 8.1

I figured that one solution would be to run a batch operation on the Eclipse JAR's which contain the icons and double their size. After a bit of tinkering, it worked. Results are pretty good - there's still a few "stubborn" icons which are tiny but most look good.

Eclipse After Processing on QHD

I put together the code into a small project: https://github.com/davidglevy/eclipse-icon-enlarger

The project works by:

  1. Iterating over every file in the eclipse base directory (specified in argument line)
  2. If a file is a directory, create a new directory under the present one in the output folder (specified in the argument line)
  3. If a file is a PNG or GIF, double
  4. If a file is another type copy
  5. If a file is a JAR or ZIP, create a target file and process the contents using a similar process: a. Images are doubled b. Other files are copied across into the ZipOutputStream as is.

The only problem I've found with this solution is that it really only works once - if you need to download plugins then do so in the original location and re-apply the icon increase batch process.

On the Dell XPS it takes about 5 minutes to run.

Happy for suggestions/improvements but this is really just an adhoc solution while we wait for the Eclipse team to get a fix out.

process.env.NODE_ENV is undefined

You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.

In the project root, run:

npm install cross-env

Then in your package.json, under scripts, add:

"start": "cross-env NODE_ENV=dev node your-app-name.js"

Then in your terminal, at the project root, start your app by running:

npm start

The environment variable will then be available in your app as process.env.NODE_ENV, so you could do something like:

if (process.env.NODE_ENV === 'dev') {
  // Your dev-only logic goes here
}

select rows in sql with latest date for each ID repeated multiple times

You can use a join to do this

SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;

Only rows which have the latest date for each ID with have a NULL join to t2.

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Centering a canvas

Given that canvas is nothing without JavaScript, use JavaScript too for sizing and positionning (you know: onresize, position:absolute, etc.)

How to print to console using swift playground?

As of Xcode 7.0.1 println is change to print. Look at the image. there are lot more we can print out. enter image description here

Prevent WebView from displaying "web page not available"

Here I found the easiest solution. check out this..

   @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
//                view.loadUrl("about:blank");
            mWebView.stopLoading();
            if (!mUtils.isInterentConnection()) {
                Toast.makeText(ReportingActivity.this, "Please Check Internet Connection!", Toast.LENGTH_SHORT).show();
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

And here is isInterentConnection() method...

public boolean isInterentConnection() {
    ConnectivityManager manager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (manager != null) {
        NetworkInfo info[] = manager.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

How can I select all children of an element except the last child?

.nav-menu li:not(:last-child){
    // write some style here
}

this code should apply the style to all

  • except the last child

  • Django: multiple models in one template using forms

    I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.

    Am I missing something here ?

    class UserProfileForm(ModelForm):
        def __init__(self, instance=None, *args, **kwargs):
            # Add these fields from the user object
            _fields = ('first_name', 'last_name', 'email',)
            # Retrieve initial (current) data from the user object
            _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
            # Pass the initial data to the base
            super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
            # Retrieve the fields from the user model and update the fields with it
            self.fields.update(fields_for_model(User, _fields))
    
        class Meta:
            model = UserProfile
            exclude = ('user',)
    
        def save(self, *args, **kwargs):
            u = self.instance.user
            u.first_name = self.cleaned_data['first_name']
            u.last_name = self.cleaned_data['last_name']
            u.email = self.cleaned_data['email']
            u.save()
            profile = super(UserProfileForm, self).save(*args,**kwargs)
            return profile
    

    Where in an Eclipse workspace is the list of projects stored?

    If you are using Perforce (imported the project as a Perforce project), then .cproject and .project will be located under the root of the PERFORCE project, not on the workspace folder.

    Hope this helps :)

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

    from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

    Personally, I wouldn't bother; I'd just rename the column.

    PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

    Determine on iPhone if user has enabled push notifications

    Though Zac's answer was perfectly correct till iOS 7, it has changed since iOS 8 arrived. Because enabledRemoteNotificationTypes has been deprecated from iOS 8 onwards. For iOS 8 and later, you need to use isRegisteredForRemoteNotifications.

    • for iOS 7 and before --> Use enabledRemoteNotificationTypes
    • for iOS 8 and later --> Use isRegisteredForRemoteNotifications.

    React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

    Make sure you're calling super() as the first thing in your constructor.

    You should set this for setAuthorState method

    class ManageAuthorPage extends Component {
    
      state = {
        author: { id: '', firstName: '', lastName: '' }
      };
    
      constructor(props) {
        super(props);
        this.handleAuthorChange = this.handleAuthorChange.bind(this);
      } 
    
      handleAuthorChange(event) {
        let {name: fieldName, value} = event.target;
    
        this.setState({
          [fieldName]: value
        });
      };
    
      render() {
        return (
          <AuthorForm
            author={this.state.author}
            onChange={this.handleAuthorChange}
          />
        );
      }
    }
    

    Another alternative based on arrow function:

    class ManageAuthorPage extends Component {
    
      state = {
        author: { id: '', firstName: '', lastName: '' }
      };
    
      handleAuthorChange = (event) => {
        const {name: fieldName, value} = event.target;
    
        this.setState({
          [fieldName]: value
        });
      };
    
      render() {
        return (
          <AuthorForm
            author={this.state.author}
            onChange={this.handleAuthorChange}
          />
        );
      }
    }
    

    What is a None value?

    I love code examples (as well as fruit), so let me show you

    apple = "apple"
    print(apple)
    >>> apple
    apple = None
    print(apple)
    >>> None
    

    None means nothing, it has no value.

    None evaluates to False.

    Stop node.js program from command line

    Though this is a late answer, I found this from NodeJS docs:

    The 'exit' event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, or by pressing <ctrl>-D to signal 'end' on the input stream. The listener callback is invoked without any arguments.

    So to summarize you can exit by:

    1. Typing .exit in nodejs REPL.
    2. Pressing <ctrl>-C twice.
    3. pressing <ctrl>-D.
    4. process.exit(0) meaning a natural exit from REPL. If you want to return any other status you can return a non zero number.
    5. process.kill(process.pid) is the way to kill using nodejs api from within your code or from REPL.

    Wait for page load in Selenium

    I don't think an implicit wait is what you want. Try this:

    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

    More information in the documentation

    How can I check if a View exists in a Database?

    To expand on Kevin's answer.

        private bool CustomViewExists(string viewName)
        {
            using (SalesPad.Data.DataConnection dc = yourconnection)
            {
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                    Select 1
                else
                    Select 0", viewName));
                cmd.CommandType = CommandType.Text;
                return Convert.ToBoolean(dc.ExecuteScalar(cmd));
            }
        }
    

    jQuery get the name of a select option

    Firstly name isn't a valid attribute of an option element. Instead you could use a data parameter, like this:

    <option value="foo" data-name="bar">Foo Bar</option>
    

    The main issue you have is that the JS is looking at the name attribute of the select element, not the chosen option. Try this:

    $('#band_type_choices').on('change', function() {         
        $('.checkboxlist').hide();
        $('#checkboxlist_' + $('option:selected', this).data("name")).css("display", "block");
    });
    

    Note the option:selected selector within the context of the select which raised the change event.

    Nullable property to entity field, Entity Framework through Code First

    Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

    To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

    // an int can never be null, so it will be created as NOT NULL in db
    public int someintfield { get; set; }
    
    // to have a nullable int, you need to declare it as an int?
    // or as a System.Nullable<int>
    public int? somenullableintfield { get; set; }
    public System.Nullable<int> someothernullableintfield { get; set; }
    

    python .replace() regex

    You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

    z.write(article[:article.index("</html>") + 7]
    

    This is much cleaner, and should be much faster than a regex based solution.

    Javascript date regex DD/MM/YYYY

    Do the following change to the jquery.validationengine-en.js file and update the dd/mm/yyyy inline validation by including leap year:

    "date": {
        // Check if date is valid by leap year
        "func": function (field) {
        //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
        var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
        var match = pattern.exec(field.val());
        if (match == null)
        return false;
    
        //var year = match[1];
        //var month = match[2]*1;
        //var day = match[3]*1;
        var year = match[3];
        var month = match[2]*1;
        var day = match[1]*1;
        var date = new Date(year, month - 1, day); // because months starts from 0.
    
        return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
    },
    "alertText": "* Invalid date, must be in DD-MM-YYYY format"
    

    Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

    If you really gotta be fast (not that I believe you do):

    char[] chars = sourceDate.toCharArray();
    chars[10] = ' ';
    String targetDate = new String(chars, 0, 19);
    

    How to list all the roles existing in Oracle database?

    all_roles.sql

    SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
         , SUBSTR(rp.grantee,1,16)              AS GRANTEE
         , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
         , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
         , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
         , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
         , SUBSTR(rtp.common,1,4)               AS COMMON
         , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
         , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
         , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
      FROM role_tab_privs rtp
      LEFT JOIN dba_role_privs rp
        ON (rtp.role = rp.granted_role)
     WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
       AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
       AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
       AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
     ORDER BY 1
            , 2
            , 3
            , 4
    ;
    

    Usage

    SQLPLUS> @all_roles '' '' '' '' '' ''
    SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
    SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
    SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
    etc.
    

    PHP order array by date?

    He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!

    <?php
     $data['may_1_2002']=
     Array(
     'title_id_32'=>'Good morning', 
     'title_id_21'=>'Blue sky',
     'title_id_3'=>'Summer',
     'date'=>'1 May 2002'
     );
    
     $data['may_2_2002']=
     Array(
     'title_id_34'=>'Leaves', 
     'title_id_20'=>'Old times',
      'date'=>'2 May   2002 '
     );
    
    
     echo '<pre>';
     print_r($data);
    ?>
    

    Spring Boot and multiple external configuration files

    If you want to override values specified in your application.properties file, you can change your active profile while you run your application and create an application properties file for the profile. So, for example, let's specify the active profile "override" and then, assuming you have created your new application properties file called "application-override.properties" under /tmp, then you can run

    java -jar yourApp.jar --spring.profiles.active="override" --spring.config.location="file:/tmp/,classpath:/" 
    

    The values especified under spring.config.location are evaluated in reverse order. So, in my example, the classpat is evaluated first, then the file value.

    If the jar file and the "application-override.properties" file are in the current directory you can actually simply use

    java -jar yourApp.jar --spring.profiles.active="override"
    

    since Spring Boot will find the properties file for you

    Add CSS3 transition expand/collapse

    OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.

    <script>
            function dostuff() {
                if (document.getElementById('MyBox').style.height == "0px") {
    
                    document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;"); 
                }
                else {
                    document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;"); 
                 }
            }
        </script>
        <div id="MyBox" style="height: 0px; width: 0px;">
        </div>
    
        <input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
    

    Using wire or reg with input or output in Verilog

    reg and wire specify how the object will be assigned and are therefore only meaningful for outputs.

    If you plan to assign your output in sequential code,such as within an always block, declare it as a reg (which really is a misnomer for "variable" in Verilog). Otherwise, it should be a wire, which is also the default.

    Can you autoplay HTML5 videos on the iPad?

    In this Safari HTML5 reference, you can read

    To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.

    What does /p mean in set /p?

    The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

    Two ways I've used it... first:

    SET /P variable=
    

    When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

    And second:

    SET /P variable=<%temp%\filename.txt
    

    Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

    reading from stdin in c++

    You have not defined the variable input_line.

    Add this:

    string input_line;
    

    And add this include.

    #include <string>
    

    Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

    #include <iostream>
    #include <string>
    
    int main() {
        for (std::string line; std::getline(std::cin, line);) {
            std::cout << line << std::endl;
        }
        return 0;
    }
    

    NULL values inside NOT IN clause

    In A, 3 is tested for equality against each member of the set, yielding (FALSE, FALSE, TRUE, UNKNOWN). Since one of the elements is TRUE, the condition is TRUE. (It's also possible that some short-circuiting takes place here, so it actually stops as soon as it hits the first TRUE and never evaluates 3=NULL.)

    In B, I think it is evaluating the condition as NOT (3 in (1,2,null)). Testing 3 for equality against the set yields (FALSE, FALSE, UNKNOWN), which is aggregated to UNKNOWN. NOT ( UNKNOWN ) yields UNKNOWN. So overall the truth of the condition is unknown, which at the end is essentially treated as FALSE.

    How do I get the current absolute URL in Ruby on Rails?

    I needed the application URL but with the subdirectory. I used:

    root_url(:only_path => false)
    

    How do I add a project as a dependency of another project?

    Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

    <project>
       ...
       <dependencies>
          <dependency>
             <groupId>yourgroup</groupId>
             <artifactId>myejbproject</artifactId>
             <version>2.0</version>
             <scope>system</scope>
             <systemPath>path/to/myejbproject.jar</systemPath>
          </dependency>
       </dependencies>
       ...
    </project>
    

    That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


    If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

    parent
    |- pom.xml
    |- MyEJBProject
    |   `- pom.xml
    `- MyWarProject
        `- pom.xml
    

    The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

    <project>
       ...
       <artifactId>myparentproject</artifactId>
       <groupId>...</groupId>
       <version>...</version>
    
       <packaging>pom</packaging>
       ...
       <modules>
         <module>MyEJBModule</module>
         <module>MyWarModule</module>
       </modules>
       ...
    </project>
    

    That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


    Finally, if your projects are not in related directories, you might try to give them as relative modules:

    filesystem
     |- mywarproject
     |   `pom.xml
     |- myejbproject
     |   `pom.xml
     `- parent
         `pom.xml
    

    now you could just do this (worked in maven 2, just tried it):

    <!--parent-->
    <project>
      <modules>
        <module>../mywarproject</module>
        <module>../myejbproject</module>
      </modules>
    </project>
    

    .NET obfuscation tools/strategy

    I am 'Knee Deep' in this now, trying to find a good solution. Here are my impressions so far.

    Xenocode - I have an old licence for Xenocode2005 which I used to use for obfuscating my .net 2.0 assemblies. It worked fine on XP and was a decent solution. My current project is .net 3.5 and I am on Vista, support told me to give it a go but the 2005 version does not even work on Vista (crashes) so I and now I have to buy 'PostBuild2008' at a gobsmacking price point of $1900. This might be a good tool but I'm not going to find out. Too expensive.

    Reactor.Net - This is a much more attractive price point and it worked fine on my Standalone Executeable. The Licencing module was also nice and would have saved me a bunch of effort. Unfortunately, It is missing a key feature and that is the ability to Exclude stuff from the obfuscation. This makes it impossible to achieve the result I needed (Merge multiple assemblies together, obfuscate some, not-Obfuscate others).

    SmartAssembly - I downloaded the Eval for this and it worked flawlessly. I was able to achieve everything I wanted and the Interface was first class. Price point is still a bit hefty.

    Dotfuscator Pro - Couldn't find price on website. Currently in discussions to get a quotation. Sounds ominous.

    Confuser - an open source project which works quite well (to confuse ppl, just as the name implies).

    Note: ConfuserEx is reportedly "broken" according to Issue #498 on their GitHub repo.

    Java Singleton and Synchronization

    Enum singleton

    The simplest way to implement a Singleton that is thread-safe is using an Enum

    public enum SingletonEnum {
      INSTANCE;
      public void doSomething(){
        System.out.println("This is a singleton");
      }
    }
    

    This code works since the introduction of Enum in Java 1.5

    Double checked locking

    If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

    public class Singleton {
    
      private static volatile Singleton instance = null;
    
      private Singleton() {
      }
    
      public static Singleton getInstance() {
        if (instance == null) {
          synchronized (Singleton.class){
            if (instance == null) {
              instance = new Singleton();
            }
          }
        }
        return instance ;
      }
    }
    

    This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

    Early loading Singleton (works even before Java 1.5)

    This implementation instantiates the singleton when the class is loaded and provides thread safety.

    public class Singleton {
    
      private static final Singleton instance = new Singleton();
    
      private Singleton() {
      }
    
      public static Singleton getInstance() {
        return instance;
      }
    
      public void doSomething(){
        System.out.println("This is a singleton");
      }
    
    }
    

    What is difference between png8 and png24

    You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

    This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

    You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

    The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

    • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
    • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
    • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
    • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
    • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

    There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

    Consistency of hashCode() on a Java string

    I can see that documentation as far back as Java 1.2.

    While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String, so changing it would count as breaking existing contracts.

    Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.

    Initializing a static std::map<int, int> in C++

    If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

    typedef std::pair< int, char > elemPair_t;
    elemPair_t elemPairs[] = 
    {
        elemPair_t( 1, 'a'), 
        elemPair_t( 3, 'b' ), 
        elemPair_t( 5, 'c' ), 
        elemPair_t( 7, 'd' )
    };
    
    const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );
    

    Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

    In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

    It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

    How to get the current location latitude and longitude in android

    You can use following class as service class to run your application in background

    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.IBinder;
    import android.widget.Toast;
    
    public class MyService extends Service {
    
        private GPSTracker gpsTracker;
        private Handler handler= new Handler();
        private Timer timer = new Timer();
        private Distance pastDistance = new Distance();
         private Distance currentDistance = new Distance();
        public static double DISTANCE;
        boolean flag = true ;
        private double totalDistance ;
        @Override
        @Deprecated
        public void onStart(Intent intent, int startId) {
    
            super.onStart(intent, startId);
            gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
            TimerTask timerTask = new TimerTask() {
    
                @Override
                public void run() {
                    handler.post(new Runnable() {
    
                        @Override
                        public void run() {
                            if(flag){
                                pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                                pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                                flag = false;
                            }else{
                                currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                                currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                                flag = comapre_LatitudeLongitude();
                            }
                            Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
    
                        }
                    });
    
    
                }
            };
    
            timer.schedule(timerTask,0, 5000);
    
        }
    
        private double distance(double lat1, double lon1, double lat2, double lon2) {
              double theta = lon1 - lon2;
              double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
              dist = Math.acos(dist);
              dist = rad2deg(dist);
              dist = dist * 60 * 1.1515;
               return (dist);
            }
    
           private double deg2rad(double deg) {
              return (deg * Math.PI / 180.0);
            }
           private double rad2deg(double rad) {
              return (rad * 180.0 / Math.PI);
       }
    
    
        @Override
        public IBinder onBind(Intent intent) {
    
            return null;
        }
    
    
    
        @Override
        public void onDestroy() {
    
            super.onDestroy();
            System.out.println("--------------------------------onDestroy -stop service ");
            timer.cancel();
            DISTANCE = totalDistance ;
        }
        public boolean comapre_LatitudeLongitude(){
    
            if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
                return false;
            }else{
    
                final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
                System.out.println("Distance in mile :"+distance);
                handler.post(new Runnable() {
    
                    @Override
                    public void run() {
                        float kilometer=1.609344f;
    
                        totalDistance = totalDistance +  distance * kilometer;
                        DISTANCE = totalDistance;
                        //Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
    
                    }
                });
    
                return true;
            }
    
        }
    
    }
    

    Add One another class to get location

    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    
    public class GPSTracker implements LocationListener {
    private final Context mContext;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location = null; 
    double latitude; 
    double longitude; 
    
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
    protected LocationManager locationManager;
    private Location m_Location;
     public GPSTracker(Context context) {
        this.mContext = context;
        m_Location = getLocation();
        System.out.println("location Latitude:"+m_Location.getLatitude());
        System.out.println("location Longitude:"+m_Location.getLongitude());
        System.out.println("getLocation():"+getLocation());
        }
    
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);
    
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } 
            else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return location;
    }
    
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
    
        return latitude;
    }
    
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
    
        return longitude;
    }
    
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    
    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    
    }
    
    
    }
    

    // --------------Distance.java

     public class Distance  {
        private double latitude ;
        private double longitude;
            public double getLatitude() {
                return latitude;
            }
            public void setLatitude(double latitude) {
                this.latitude = latitude;
            }
            public double getLongitude() {
                return longitude;
            }
            public void setLongitude(double longitude) {
                this.longitude = longitude;
            }
    
    
    
    }
    

    Maven does not find JUnit tests to run

    If your test class name does not follow the standard naming convention (as highlighted by @axtavt above), you need to add the pattern/class name in the pom.xml in order to Maven pick the test -

    ...
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*_UT.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build> 
    ...
    

    Java: set timeout on a certain block of code?

    I faced a similar kind of issue where my task was to push a message to SQS within a particular timeout. I used the trivial logic of executing it via another thread and waiting on its future object by specifying the timeout. This would give me a TIMEOUT exception in case of timeouts.

    final Future<ISendMessageResult> future = 
    timeoutHelperThreadPool.getExecutor().submit(() -> {
      return getQueueStore().sendMessage(request).get();
    });
    try {
      sendMessageResult = future.get(200, TimeUnit.MILLISECONDS);
      logger.info("SQS_PUSH_SUCCESSFUL");
      return true;
    
    } catch (final TimeoutException e) {
      logger.error("SQS_PUSH_TIMEOUT_EXCEPTION");
    }
    

    But there are cases where you can't stop the code being executed by another thread and you get true negatives in that case.

    For example - In my case, my request reached SQS and while the message was being pushed, my code logic encountered the specified timeout. Now in reality my message was pushed into the Queue but my main thread assumed it to be failed because of the TIMEOUT exception. This is a type of problem which can be avoided rather than being solved. Like in my case I avoided it by providing a timeout which would suffice in nearly all of the cases.

    If the code you want to interrupt is within you application and is not something like an API call then you can simply use

    future.cancel(true)
    

    However do remember that java docs says that it does guarantee that the execution will be blocked.

    "Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled,or could not be cancelled for some other reason. If successful,and this task has not started when cancel is called,this task should never run. If the task has already started,then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted inan attempt to stop the task."

    Excel VBA - read cell value from code

    I think you need this ..

    Dim n as Integer   
    
    For n = 5 to 17
      msgbox cells(n,3) '--> sched waste
      msgbox cells(n,4) '--> type of treatm
      msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
      msgbox cells(n,6) '--> email col
    Next
    

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

    I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

    [src=''] {
        visibility: hidden;
    }
    

    Python list iterator behavior and next(iterator)

    Something is wrong with your Python/Computer.

    a = iter(list(range(10)))
    for i in a:
       print(i)
       next(a)
    
    >>> 
    0
    2
    4
    6
    8
    

    Works like expected.

    Tested in Python 2.7 and in Python 3+ . Works properly in both

    How to create a property for a List<T>

    Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.

    public class MyClass<T>
    {
      etc
    

    How to track untracked content?

    This worked out just fine for me:

    git update-index --skip-worktree

    If it doesn't work with the pathname, try the filename. Let me know if this worked for you too.

    Bye!

    CSS text-overflow in a table cell?

    If you just want the table to auto-layout

    Without using max-width, or percentage column widths, or table-layout: fixed etc.

    https://jsfiddle.net/tturadqq/

    How it works:


    Step 1: Just let the table auto-layout do its thing.

    When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:

    enter image description here


    Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em

    (the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')

    enter image description here


    Step 3: Set title on the divs

    This is good for accessibility, and is necessary for the little trick we'll use in a moment.

    enter image description here


    Step 4: Add a CSS ::after on the div

    This is the tricky bit. We set a CSS ::after, with content: attr(title), then position that on top of the div and set text-overflow: ellipsis. I've coloured it red here to make it clear.

    (Note how the long column now has a tailing ellipsis)

    enter image description here


    Step 5: Set the colour of the div text to transparent

    And we're done!

    enter image description here

    understanding private setters

    Yes, you are using encapsulation by using properties, but there are more nuances to encapsulation than just taking control over how properties are read and written. Denying a property to be set from outside the class can be useful both for robustness and performance.

    An immutable class is a class that doesn't change once it's created, so private setters (or no setters at all) is needed to protect the properties.

    Private setters came into more frequent use with the property shorthand that was instroduced in C# 3. In C# 2 the setter was often just omitted, and the private data accessed directly when set.

    This property:

    public int Size { get; private set; }
    

    is the same as:

    private int _size;
    public int Size {
      get { return _size; }
      private set { _size = value; }
    }
    

    except, the name of the backing variable is internally created by the compiler, so you can't access it directly.

    With the shorthand property the private setter is needed to create a read-only property, as you can't access the backing variable directly.

    Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

    I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

    =(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))
    

    How to remove text before | character in notepad++

    To replace anything that starts with "text" until the last character:

    text.+(.*)$

    Example

    text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                          ^
                                                          last character


    To replace anything that starts with "text" until "123"

    text.+(\ 123)

    Example

    text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
    ^                                   ^
    From here                     To here

    No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

    I got the following error:

    org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
        at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
    

    I fixed this by changing my hibernate properties file

    hibernate.current_session_context_class=thread
    

    My code and configuration file as follows

    session =  getHibernateTemplate().getSessionFactory().getCurrentSession();
    
    session.beginTransaction();
    
    session.createQuery(Qry).executeUpdate();
    
    session.getTransaction().commit();
    

    on properties file

    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    
    hibernate.show_sql=true
    
    hibernate.query_factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
    
    hibernate.current_session_context_class=thread
    

    on cofiguration file

    <properties>
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>         
    <prop key="hibernate.query.factory_class">${hibernate.query_factory_class}</prop>       
    <prop key="hibernate.generate_statistics">true</prop>
    <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
    </props>
    </property>
    </properties>
    

    Thanks,
    Ashok

    Make columns of equal width in <table>

    Found this on HTML table: keep the same width for columns

    If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .

    Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

    Got the solution and it's working fine. Set the environment variables as:

    • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
    • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
    • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
    • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

    Ternary operator (?:) in Bash

    (( a = b==5 ? c : d )) # string + numeric
    

    Error: «Could not load type MvcApplication»

    [Extracted from question]

    If you are getting this error: "Could not load type MvcApplication", look at the Output path of your project and make sure it is set to 'bin\'. The problem is that the AspNetCompiler cannot find the files if they are not in the default location.

    Another side effect of changing the output folder is that you will not be able to debug your code and it comes up with a message saying that the Assembly info cannot be found.

    EF Core add-migration Build Failed

    I got the same error. I fixed it by stopping the project build. After that it worked fine.

    nginx 502 bad gateway

    Try disabling the xcache or apc modules. Seems to cause a problem with some versions are saving objects to a session variable.

    Android Webview - Webpage should fit the device screen

    These settings worked for me:

    wv.setInitialScale(1);
    wv.getSettings().setLoadWithOverviewMode(true);
    wv.getSettings().setUseWideViewPort(true);
    wv.getSettings().setJavaScriptEnabled(true);
    

    setInitialScale(1) was missing in my attempts.

    Although documentation says that 0 will zoom all the way out if setUseWideViewPort is set to true but 0 did not work for me and I had to set 1.

    Allow docker container to connect to a local/host postgres database

    The solution posted here does not work for me. Therefore, I am posting this answer to help someone facing similar issue.

    OS: Ubuntu 18
    PostgreSQL: 9.5 (Hosted on Ubuntu)
    Docker: Server Application (which connects to PostgreSQL)

    I am using docker-compose.yml to build application.

    STEP 1: Please add host.docker.internal:<docker0 IP>

    version: '3'
    services:
      bank-server:
        ...
        depends_on:
          ....
        restart: on-failure
        ports:
          - 9090:9090
        extra_hosts:
          - "host.docker.internal:172.17.0.1"
    

    To find IP of docker i.e. 172.17.0.1 (in my case) you can use:

    $> ifconfig docker0
    docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
            inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
    

    OR

    $> ip a
    1: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
        inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
           valid_lft forever preferred_lft forever
    

    STEP 2: In postgresql.conf, change listen_addresses to listen_addresses = '*'

    STEP 3: In pg_hba.conf, add this line

    host    all             all             0.0.0.0/0               md5
    

    STEP 4: Now restart postgresql service using, sudo service postgresql restart

    STEP 5: Please use host.docker.internal hostname to connect database from Server Application.
    Ex: jdbc:postgresql://host.docker.internal:5432/bankDB

    Enjoy!!

    Android intent for playing video?

    From now onwards after API 24, Uri.parse(filePath) won't work. You need to use this

    final File videoFile = new File("path to your video file");
    Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(fileUri, "video/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
    startActivity(intent);
    

    But before using this you need to understand how file provider works. Go to official document link to understand file provider better.

    Select data between a date/time range

    MySQL date format is this : Y-M-D. You are using Y/M/D. That's is wrong. modify your query.

    If you insert the date like Y/M/D, It will be insert null value in the database.

    If you are using PHP and date you are getting from the form is like this Y/M/D, you can replace this with using the statement .

    out_date=date('Y-m-d', strtotime(str_replace('/', '-', $data["input_date"])))
    

    Commands out of sync; you can't run this command now

    I call this function every time before using $mysqli->query Works with stored procedures as well.

    function clearStoredResults(){
        global $mysqli;
    
        do {
             if ($res = $mysqli->store_result()) {
               $res->free();
             }
            } while ($mysqli->more_results() && $mysqli->next_result());        
    
    }
    

    Getting multiple values with scanf()

    Could do this, but then the user has to separate the numbers by a space:

    #include "stdio.h"
    
    int main()
    {
        int minx, x, y, z;
    
        printf("Enter four ints: ");
        scanf( "%i %i %i %i", &minx, &x, &y, &z);
    
        printf("You wrote: %i %i %i %i", minx, x, y, z);
    }
    

    How to read keyboard-input?

    try

    raw_input('Enter your input:')  # If you use Python 2
    input('Enter your input:')      # If you use Python 3
    

    and if you want to have a numeric value just convert it:

    try:
        mode=int(raw_input('Input:'))
    except ValueError:
        print "Not a number"
    

    Ruby/Rails: converting a Date to a UNIX timestamp

    I get the following when I try it:

    >> Date.today.to_time.to_i
    => 1259244000
    >> Time.now.to_i
    => 1259275709
    

    The difference between these two numbers is due to the fact that Date does not store the hours, minutes or seconds of the current time. Converting a Date to a Time will result in that day, midnight.

    Does Java support default parameter values?

    I might be stating the obvious here but why not simply implement the "default" parameter yourself?

    public class Foo() {
            public void func(String s){
                    func(s, true);
            }
            public void func(String s, boolean b){
                    //your code here
            }
    }
    

    for the default, you would either use

    func("my string");
    

    and if you wouldn't like to use the default, you would use

    func("my string", false);
    

    How to make the window full screen with Javascript (stretching all over the screen)

    You can use The fullscreen API You can see an example here

    The fullscreen API provides an easy way for web content to be presented using the user's entire screen. This article provides information about using this API.

    Remove all constraints affecting a UIView

    Based on previous answers (swift 4)

    You can use immediateConstraints when you don't want to crawl entire hierarchies.

    extension UIView {
    /**
     * Deactivates immediate constraints that target this view (self + superview)
     */
    func deactivateImmediateConstraints(){
        NSLayoutConstraint.deactivate(self.immediateConstraints)
    }
    /**
     * Deactivates all constrains that target this view
     */
    func deactiveAllConstraints(){
        NSLayoutConstraint.deactivate(self.allConstraints)
    }
    /**
     * Gets self.constraints + superview?.constraints for this particular view
     */
    var immediateConstraints:[NSLayoutConstraint]{
        let constraints = self.superview?.constraints.filter{
            $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
            } ?? []
        return self.constraints + constraints
    }
    /**
     * Crawls up superview hierarchy and gets all constraints that affect this view
     */
    var allConstraints:[NSLayoutConstraint] {
        var view: UIView? = self
        var constraints:[NSLayoutConstraint] = []
        while let currentView = view {
            constraints += currentView.constraints.filter {
                return $0.firstItem as? UIView === self || $0.secondItem as? UIView === self
            }
            view = view?.superview
        }
        return constraints
    }
    }
    

    Some dates recognized as dates, some dates not recognized. Why?

    In your case it is probably taking them in DD-MM-YY format, not MM-DD-YY.

    MVC controller : get JSON object from HTTP body?

    I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.

    I needed the following to get it to work:

    • controller action

      [HttpPost]
      [PermitAllUsers]
      [Route("Models")]
      public JsonResult InsertOrUpdateModels(Model entities)
      {
          // ...
          return Json(response, JsonRequestBehavior.AllowGet);
      }
      
    • a Models class

      public class Model
      {
          public string Test { get; set; }
          // ...
      }
      
    • headers for Postman's request, specifically, Content-Type

      postman headers

    • json in the request body

      enter image description here

    How to Lazy Load div background images

    I know it's not related to the image load but here what I did in one of the job interview test.

    HTML

    <div id="news-feed">Scroll to see News (Newest First)</div>
    

    CSS

    article {
       margin-top: 500px;
       opacity: 0;
       border: 2px solid #864488;
       padding: 5px 10px 10px 5px;
       background-image: -webkit-gradient(
       linear,
       left top,
       left bottom,
       color-stop(0, #DCD3E8),
       color-stop(1, #BCA3CC)
       );
       background-image: -o-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
       background-image: -moz-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
       background-image: -webkit-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
       background-image: -ms-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
       background-image: linear-gradient(to bottom, #DCD3E8 0%, #BCA3CC 100%);
       color: gray;
       font-family: arial;    
    }
    
    article h4 {
       font-family: "Times New Roman";
       margin: 5px 1px;
    }
    
    .main-news {
       border: 5px double gray;
       padding: 15px;
    }
    

    JavaScript

    var newsData,
        SortData = '',
        i = 1;
    
    $.getJSON("http://www.stellarbiotechnologies.com/media/press-releases/json", function(data) {
    
       newsData = data.news;
    
       function SortByDate(x,y) {
         return ((x.published == y.published) ? 0 : ((x.published < y.published) ? 1 : -1 ));
       }
    
       var sortedNewsData = newsData.sort(SortByDate);
    
       $.each( sortedNewsData, function( key, val ) {
         SortData += '<article id="article' + i + '"><h4>Published on: ' + val.published + '</h4><div  class="main-news">' + val.title + '</div></article>';
         i++;    
       });
    
       $('#news-feed').append(SortData);
    });
    
    $(window).scroll(function() {
    
       var $window = $(window),
           wH = $window.height(),
           wS = $window.scrollTop() + 1
    
       for (var j=0; j<$('article').length;j++) {
          var eT = $('#article' + j ).offset().top,
              eH = $('#article' + j ).outerHeight();
    
              if (wS > ((eT + eH) - (wH))) {
                 $('#article' + j ).animate({'opacity': '1'}, 500);
              }
        }
    
    });
    

    I am sorting the data by Date and then doing lazy load on window scroll function.

    I hope it helps :)

    Demo

    Effective method to hide email from spam bots

    I think the only foolproof method you can have is creating a Contact Me page that is a form that submits to a script that sends to your email address. That way, your address is never exposed to the public at all. This may be undesirable for some reason, but I think it's a pretty good solution. It often irks me when I'm forced to copy/paste someone's email address from their site to my mail client and send them a message; I'd rather do it right through a form on their site. Also, this approach allows you to have anonymous comments sent to you, etc. Just be sure to protect your form using some kind of anti-bot scheme, such as a captcha. There are plenty of them discussed here on SO.

    How can I add new keys to a dictionary?

    Here's another way that I didn't see here:

    >>> foo = dict(a=1,b=2)
    >>> foo
    {'a': 1, 'b': 2}
    >>> goo = dict(c=3,**foo)
    >>> goo
    {'c': 3, 'a': 1, 'b': 2}
    

    You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

    >>> foo = dict(a=1,b=2,c=3,d=4)
    >>> new_dict = {k: v for k, v in list(foo.items())[:2]}
    >>> new_dict
    {'a': 1, 'b': 2}
    >>> new_dict.update(newvalue=99)
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99}
    >>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
    >>> 
    

    The above is using dictionary comprehension.

    Adding a Scrollable JTextArea (Java)

    A scroll pane is a container which contains another component. You can't add your text area to two different scroll panes. The scroll pane takes care of the horizontal and vertical scroll bars.

    And if you never add the scroll pane to the frame, it will never be visible.

    Read the swing tutorial about scroll panes.

    Server cannot set status after HTTP headers have been sent IIS7.5

    Just to add to the responses above. I had this same issue when i first started using ASP.Net MVC and i was doing a Response.Redirect during a controller action:

    Response.Redirect("/blah", true);
    

    Instead of returning a Response.Redirect action i should have been returning a RedirectAction:

    return Redirect("/blah");
    

    Why do I have to "git push --set-upstream origin <branch>"?

    My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.

    Push and set upstream (remote) repository as origin:

    $ git push -u origin
    

    Next time you push, you don't have to specify the remote repository:

    $ git push
    

    Getting Textarea Value with jQuery

    try this:

    <a id="send-thoughts" href="">Click</a>
    <textarea id="message"></textarea>
    <!--<textarea id="#message"></textarea>-->
    
                jQuery("a#send-thoughts").click(function() {
                    //var thought = jQuery("textarea#message").val();
                    var thought = $("#message").val();
                    alert(thought);
                });
    

    PermissionError: [Errno 13] in python

    When doing;

    a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
    

    ...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

    Your other example though;

    a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
    

    should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

    a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
    

    Converting a char to uppercase

    I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.

    Can be done through StringBuffer:

    public static String toFirstLastCharUpperAll(String string){
        StringBuffer sb=new StringBuffer(string);
            for(int i=0;i<sb.length();i++)
                if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
                    || i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
                    sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
         return sb.toString();
    }
    

    How do I get IntelliJ to recognize common Python modules?

    Here's what I had to do. (And I probably forgot an important aspect of my problem, which is that this wasn't set up as a Python project originally, but a Java project, with some python files in them.)

    Project Settings -> Modules -> Plus button (add a module) -> Python

    Then, click the "..." button next to Python Interpreter.

    In the "Configure SDK" dialog that pops up, click the "+" button. Select "Python SDK", then select the default "Python" shortcut that appears in my finder dialog

    Wait about 5 minutes. Read some productivity tips. :)

    Click Ok

    Wait for the system to rebuild some indexes.

    Hooray! Code hinting is back for my modules!

    No signing certificate "iOS Distribution" found

    Goto Xcode -> Prefrences and import the profile enter image description here

    Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

    I believe that a much more reliable way to detect mobile devices is to look at the navigator.userAgent string. For example, on my iPhone the user agent string is:

    Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1

    Note that this string contains two telltale keywords: iPhone and Mobile. Other user agent strings for devices that I don't have are provided at:

    https://deviceatlas.com/blog/list-of-user-agent-strings

    Using this string, I set a JavaScript Boolean variable bMobile on my website to either true or false using the following code:

    var bMobile =   // will be true if running on a mobile device
      navigator.userAgent.indexOf( "Mobile" ) !== -1 || 
      navigator.userAgent.indexOf( "iPhone" ) !== -1 || 
      navigator.userAgent.indexOf( "Android" ) !== -1 || 
      navigator.userAgent.indexOf( "Windows Phone" ) !== -1 ;
    

    launch sms application with an intent

    try {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setData(Uri.parse("smsto:" + Uri.encode(number)));
        smsIntent.putExtra("address", number);
        smsIntent.putExtra("sms_body", message);
    
        PackageManager pm = activity.getPackageManager();
        List<ResolveInfo> resInfo = pm.queryIntentActivities(smsIntent, 0);
    
        for (int i = 0; i < resInfo.size(); i++) {
            ResolveInfo ri = resInfo.get(i);
            String packageName = ri.activityInfo.packageName;
    
            if (packageName.contains("sms")) {
                //Log.d("TAG", packageName + " : " + ri.activityInfo.name);
                smsIntent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            }
        }
        activity.startActivity(smsIntent);
    } catch (Exception e) {
        // Handle Error
    }
    

    Best way of doing this.

    Text editor to open big (giant, huge, large) text files

    Tips and tricks

    less

    Why are you using editors to just look at a (large) file?

    Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

    There is a Win32 port of GNU less. See the "less" section of the answer above.

    Perl

    Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

    For example:

    $ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less
    

    This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

    Another example:

    $ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less
    

    This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

    logparser

    This is another useful tool you can use. To quote the Wikipedia article:

    logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

    Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

    Example usage:

    C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
    C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"
    

    The relativity of sizes

    100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

    And more...

    Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

    How to make div go behind another div?

    http://jsfiddle.net/f2znvn4f/


    HTML

    <div class="box-left-mini">
        <div class="front"><span>this is in front</span></div>
        <div class="behind_container">
            <div class="behind">behind</div>        
        </div>
    </div>
    

    CSS

    .box-left-mini{
        float:left;
        background-image:url(website-content/hotcampaign.png);
        width:292px;
        height:141px;
    }
    
    .box-left-mini .front {
        display: block;
        z-index: 5;
        position: relative;
    }
    .box-left-mini .front span {
        background: #fff
    }
    
    .box-left-mini .behind_container {
        background-color: #ff0;
        position: relative;
        top: -18px;
    }
    .box-left-mini .behind {
        display: block;
        z-index: 3;
    }
    

    The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

    Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

    I solved this issue to update .htaccess file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess in my case).

    Just update or add this php_value max_execution_time 300 line before # END WordPress. Then save the file and try to install again.

    If the error occurs again, you can maximize the value from 300 to 600.

    Reverting single file in SVN to a particular revision

    I found it's simple to do this via the svn cat command so that you don't even have to specify a revision.

    svn cat mydir/myfile > mydir/myfile
    

    This probably won't role back the inode (metadata) data such as timestamps.

    Why use def main()?

    "What does if __name__==“__main__”: do?" has already been answered.

    Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.

    Node.js for() loop returning the same values at each loop

    I would suggest doing this in a more functional style :P

    function CreateMessageboard(BoardMessages) {
      var htmlMessageboardString = BoardMessages
       .map(function(BoardMessage) {
         return MessageToHTMLString(BoardMessage);
       })
       .join('');
    }
    

    Try this

    Can you call ko.applyBindings to bind a partial view?

    While Niemeyer's answer is a more correct answer to the question, you could also do the following:

    <div>
      <input data-bind="value: VMA.name" />
    </div>
    
    <div>
      <input data-bind="value: VMB.name" />
    </div>
    
    <script type="text/javascript">
      var viewModels = {
         VMA: {name: ko.observable("Bob")},
         VMB: {name: ko.observable("Ted")}
      };
    
      ko.applyBindings(viewModels);
    </script>
    

    This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:

    <div>
      <input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
    </div>
    

    Rotate a div using javascript

    I recently had to build something similar. You can check it out in the snippet below.

    The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

    Basically, my code looks like this...

    Run Code Snippet

    _x000D_
    _x000D_
    var rocket = document.querySelector('.rocket');_x000D_
    var btn = document.querySelector('.toggle');_x000D_
    var rotate = false;_x000D_
    var runner;_x000D_
    var degrees = 0;_x000D_
    _x000D_
    function start(){_x000D_
        runner = setInterval(function(){_x000D_
            degrees++;_x000D_
            rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
        },50)_x000D_
    }_x000D_
    _x000D_
    function stop(){_x000D_
        clearInterval(runner);_x000D_
    }_x000D_
    _x000D_
    btn.addEventListener('click', function(){_x000D_
        if (!rotate){_x000D_
            rotate = true;_x000D_
            start();_x000D_
        } else {_x000D_
            rotate = false;_x000D_
            stop();_x000D_
        }_x000D_
    })
    _x000D_
    body {_x000D_
      background: #1e1e1e;_x000D_
    }    _x000D_
    _x000D_
    .rocket {_x000D_
        width: 150px;_x000D_
        height: 150px;_x000D_
        margin: 1em;_x000D_
        border: 3px dashed teal;_x000D_
        border-radius: 50%;_x000D_
        background-color: rgba(128,128,128,0.5);_x000D_
        display: flex;_x000D_
        justify-content: center;_x000D_
        align-items: center;_x000D_
      }_x000D_
      _x000D_
      .rocket h1 {_x000D_
        margin: 0;_x000D_
        padding: 0;_x000D_
        font-size: .8em;_x000D_
        color: skyblue;_x000D_
        letter-spacing: 1em;_x000D_
        text-shadow: 0 0 10px black;_x000D_
      }_x000D_
      _x000D_
      .toggle {_x000D_
        margin: 10px;_x000D_
        background: #000;_x000D_
        color: white;_x000D_
        font-size: 1em;_x000D_
        padding: .3em;_x000D_
        border: 2px solid red;_x000D_
        outline: none;_x000D_
        letter-spacing: 3px;_x000D_
      }
    _x000D_
    <div class="rocket"><h1>SPIN ME</h1></div>_x000D_
    <button class="toggle">I/0</button>
    _x000D_
    _x000D_
    _x000D_

    How to adjust layout when soft keyboard appears

    It can work for all kind of layout.

    1. add this to your activity tag in AndroidManifest.xml

    android:windowSoftInputMode="adjustResize"

    for example:

    <activity android:name=".ActivityLogin"
        android:screenOrientation="portrait"
        android:theme="@style/AppThemeTransparent"
        android:windowSoftInputMode="adjustResize"/>
    
    1. add this on your layout tag in activitypage.xml that will change its position.

    android:fitsSystemWindows="true"

    and

    android:layout_alignParentBottom="true"

    for example:

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:fitsSystemWindows="true">
    

    How to create a file on Android Internal Storage?

    Hi try this it will create directory + file inside it

    File mediaDir = new File("/sdcard/download/media");
    if (!mediaDir.exists()){
        mediaDir.mkdir();
    }
    
    File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
    resolveMeSDCard.createNewFile();
    FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
    fos.write(string.getBytes());
    fos.close();
    
    System.out.println("Your file has been written");  
    

    How to recover closed output window in netbeans?

    in Netbeans 7.4 try Window -> Output OR Ctrl + 4

    Get first and last day of month using threeten, LocalDate

    Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:

    import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
    
    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);
    LocalDate end = initial.with(lastDayOfMonth());
    

    Syntax for a single-line Bash infinite while loop

    You don't even need to use do and done. For infinite loops I find it more readable to use for with curly brackets. For example:

    for ((;;)) { date ; sleep 1 ; }
    

    This works in bash and zsh. Doesn't work in sh.

    How do I add items to an array in jQuery?

    Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

    var list = new Array();
    $.getJSON("json.js", function(data) {
        $.each(data, function(i, item) {
            console.log(item.text);
            list.push(item.text);
        });
        console.log(list.length);
    });
    

    c++ custom compare function for std::sort()

    std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

    Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

    std::vector<pair<K,V>> items; 
    std::sort(items.begin(), items.end()); 
    

    If you really need to provide your own comparison function, then you need something along the lines of

    template <typename K, typename V>
    bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
    {
      return lhs.first < rhs.first;
    }
    

    How to change the color of a CheckBox?

    You should try below code. It is working for me.

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/checked" 
              android:state_checked="true">
            <color android:color="@color/yello" />
        </item>
        <!-- checked -->
        <item android:drawable="@drawable/unchecked" 
              android:state_checked="false">
            <color android:color="@color/black"></color>
        </item>
        <!-- unchecked -->
        <item android:drawable="@drawable/checked" 
              android:state_focused="true">
            <color android:color="@color/yello"></color>
        </item>
        <!-- on focus -->
        <item android:drawable="@drawable/unchecked">
            <color android:color="@color/black"></color>
        </item>
        <!-- default -->
    </selector>
    

    and CheckBox

    <CheckBox
        Button="@style/currentcy_check_box_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:text="@string/step_one_currency_aud" />
    

    Date to milliseconds and back to date in Swift

    As @Travis Solution works but in some cases

    var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

    with error

    Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

    Here is Updated Answer

    extension Date {
     var millisecondsSince1970:Int64 {
            return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
            //RESOLVED CRASH HERE
        }
    
        init(milliseconds:Int) {
            self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
        }
    }
    

    About Int definitions.

    On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

    Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

    Hope it is helpful to someone who also has same problem

    How to center an iframe horizontally?

    Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally. Give me THUMBS UP VOTE if you like.?.

    style > img & iframe > this is your tag name so change that if you're want any other tag in center

    _x000D_
    _x000D_
    <html >_x000D_
     <head> _x000D_
                <style type=text/css>_x000D_
                div{}_x000D_
                img{_x000D_
                     margin: 0 auto;_x000D_
              display:block;_x000D_
              }_x000D_
      iframe{ _x000D_
      margin: 0 auto;_x000D_
      display:block;_x000D_
      }_x000D_
        _x000D_
                </style>_x000D_
    </head>_x000D_
     <body >_x000D_
               _x000D_
       <iframe src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" width="320" height="180" frameborder="0" allowfullscreen="allowfullscreen"></iframe> _x000D_
       _x000D_
       <img src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg" width="320" height="180"  />_x000D_
                </body> _x000D_
                </html>
    _x000D_
    _x000D_
    _x000D_

    Unexpected 'else' in "else" error

    I would suggest to read up a bit on the syntax. See here.

    if (dsnt<0.05) {
      wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
    } else if (dst<0.05) {
        wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
    } else 
      t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)