Programs & Examples On #Executionengineexception

Application Crashes With "Internal Error In The .NET Runtime"

In my case this exception was occured when disk space was over and .NET can't allocate memory in Windows Virtual Memory.

In event log I saw this error:

Application popup: Windows - Virtual Memory Minimum Too Low : Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied.

And previous error:

The C: disk is at or near capacity. You may need to delete some files.

Run php script as daemon process

Extending Emil Ivaov answer, You can do the following to close STDIN, STDOUT AND STDERROR in php

if (!fclose(STDIN)) {
    exit("Could not close STDIN");
}

if (!fclose(STDOUT)) {
    exit("Could not close STDOUT");
}

if (!fclose(STDERR)) {
    exit("Could not close STDERR");
}

$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen('/dev/null', 'w');
$STDERR = fopen('/var/log/our_error.log', 'wb');

Basically you close the standard streams so that PHP has no place to write. The following fopen calls will set the standard IO to /dev/null.

I have read this from book of Rob Aley - PHP beyond the web

Bootstrap 3 unable to display glyphicon properly

the icons and the css are now seperated out from bootstrap. here is a fiddle that is from another stackoverflow answer

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc2/css/bootstrap-glyphicons.css");

http://jsfiddle.net/aQrPd/1/

Bootstrap 3 Glyphicons CDN

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

How to use componentWillMount() in React Hooks?

As it has been stated in react document:

You might be thinking that we’d need a separate effect to perform the cleanup. But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up:

useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

so the only thing that we need to have the componentWillUnmount in hooks is to return a function inside a useEffect, as explained above.

Docker Compose wait for container X before starting Y

Here is the example where main container waits for worker when it start responding for pings:

version: '3'
services:
  main:
    image: bash
    depends_on:
     - worker
    command: bash -c "sleep 2 && until ping -qc1 worker; do sleep 1; done &>/dev/null"
    networks:
      intra:
        ipv4_address: 172.10.0.254
  worker:
    image: bash
    hostname: test01
    command: bash -c "ip route && sleep 10"
    networks:
      intra:
        ipv4_address: 172.10.0.11
networks:
  intra:
    driver: bridge
    ipam:
      config:
      - subnet: 172.10.0.0/24

However, the proper way is to use healthcheck (>=2.1).

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

CSS Font Border?

You could perhaps emulate a text-stroke, using the css text-shadow (or -webkit-text-shadow/-moz-text-shadow) and a very low blur:

#element
{
  text-shadow: 0 0 2px #000; /* horizontal-offset vertical-offset 'blur' colour */
  -moz-text-shadow: 0 0 2px #000;
  -webkit-text-shadow: 0 0 2px #000;
}

But while this is more widely available than the -webkit-text-stroke property, I doubt that it's available to the majority of your users, but that might not be a problem (graceful degradation, and all that).

cannot find zip-align when publishing app

When I was completely desperate, I did the following, that allowed me to find official zipalign.exe. The short answer is to use the link from official (but not public :-) part of of the site:

https://dl.google.com/android/repository/build-tools_r28-rc1-windows.zip

If you use this recepy after 2018, you probably need the full explanation:

  1. Open Android Studio and go

    Android Studio->Tools->Android->SDK Manager->Android SDK->SDK update site
    
  2. Write in text editor link and open it in the browser. In my case the first link worked for me:

    https://dl.google.com/android/repository/repository2-1.xml
    
  3. Look for the latest package build-tools. In my case, it was build-tools_r28-rc1-windows.zip, but you can find the latest in your time

    Ctrl+F build-tools_
    
  4. Substitute in the URL the last part with the found package name like I did:

    https://dl.google.com/android/repository/build-tools_r28-rc1-windows.zip
    
  5. Download the package, unzip it and fortunately find official file:

    zipalign.exe
    

If it helps you, your feedback is wellcome.

How to get mouse position in jQuery without mouse-events?

var CurrentMouseXPostion;
var CurrentMouseYPostion;

$(document).mousemove(function(event) {
    CurrentMouseXPostion = event.pageX;
    CurrentMouseYPostion = event.pageY;
});

Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

make a phone call click on a button

To have the code within one line, try this:

startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:123456789")));

along with the proper manifest permission:

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

Hope this helps!

Automatically scroll down chat div

I prefer to use Vanilla JS

let chatWrapper = document.querySelector('#chat-messages');
chatWrapper.scrollTo(0, chatWrapper.offsetHeight );

where element.scrollTo(x-coord, y-coord)

Is it necessary to write HEAD, BODY and HTML tags?

Omitting the html, head, and body tags is certainly allowed by the HTML specs. The underlying reason is that browsers have always sought to be consistent with existing web pages, and the very early versions of HTML didn't define those elements. When HTML 2.0 first did, it was done in a way that the tags would be inferred when missing.

I often find it convenient to omit the tags when prototyping and especially when writing test cases as it helps keep the mark-up focused on the test in question. The inference process should create the elements in exactly the manner that you see in Firebug, and browsers are pretty consistent in doing that.

But...

IE has at least one known bug in this area. Even IE9 exhibits this. Suppose the markup is this:

<!DOCTYPE html>
<title>Test case</title>
<form action='#'>
   <input name="var1">
</form>

You should (and do in other browsers) get a DOM that looks like this:

HTML
    HEAD
        TITLE
    BODY
        FORM action="#"
            INPUT name="var1"

But in IE you get this:

HTML
    HEAD
       TITLE
       FORM action="#"
           BODY
               INPUT name="var1"
    BODY

See it for yourself.

This bug seems limited to the form start tag preceding any text content and any body start tag.

Upload folder with subfolders using S3 and the AWS console

I do not see Python answers here. You can script folder upload using Python/boto3. Here's how to recursively get all file names from directory tree:

def recursive_glob(treeroot, extention):
    results = [os.path.join(dirpath, f)
        for dirpath, dirnames, files in os.walk(treeroot)
        for f in files if f.endswith(extention)]
    return results

Here's how to upload a file to S3 using Python/boto:

k = Key(bucket)
k.key = s3_key_name
k.set_contents_from_file(file_handle, cb=progress, num_cb=20, reduced_redundancy=use_rr )

I used these ideas to write Directory-Uploader-For-S3

Wait until all promises complete even if some rejected

I really like Benjamin's answer, and how he basically turns all promises into always-resolving-but-sometimes-with-error-as-a-result ones. :)
Here's my attempt at your request just in case you were looking for alternatives. This method simply treats errors as valid results, and is coded similar to Promise.all otherwise:

Promise.settle = function(promises) {
  var results = [];
  var done = promises.length;

  return new Promise(function(resolve) {
    function tryResolve(i, v) {
      results[i] = v;
      done = done - 1;
      if (done == 0)
        resolve(results);
    }

    for (var i=0; i<promises.length; i++)
      promises[i].then(tryResolve.bind(null, i), tryResolve.bind(null, i));
    if (done == 0)
      resolve(results);
  });
}

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Solution 1 - you need to change your backend to accept your incoming requests

Solution 2 - using Angular proxy see here

Please note this is only for ng serve, you can't use proxy in ng build

Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.

How to clear jQuery validation error messages?

In my case helped with approach:

$(".field-validation-error span").hide();

Formatting floats without trailing zeros

>>> str(a if a % 1 else int(a))

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

javac: invalid target release: 1.8

I got the same issue in IntelliJ IDEA Community with Maven and I had to reimport the project by right-clicking the project in the Project tab -> Maven -> Reimport

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

http://www.php.net/manual/en/mbstring.installation.php

Can multiple different HTML elements have the same ID if they're different elements?

No. two elements with the same id are not valid. IDs are unique, if you wish to do something like that, use a class. Don't forget that elements can have multiple classes by using a space as a delimeter:

<div class="myclass sexy"></div>

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to set the style -webkit-transform dynamically using JavaScript?

If you want to do it via setAttribute you would change the style attribute like so:

element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc

This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:

element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';

The above is equivalent to

element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';

How do I write a custom init for a UIView subclass in Swift?

I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

Here's what I do:

@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}

AttributeError("'str' object has no attribute 'read'")

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Execution sequence of Group By, Having and Where clause in SQL Server?

In below Order

  1. FROM & JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

Scroll to a specific Element Using html

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

_tkinter.TclError: no display name and no $DISPLAY environment variable

In order to see images, plots and anything displayed on windows on your remote machine you need to connect to it like this:

ssh -X user@hostname

That way you enable the access to the X server. The X server is a program in the X Window System that runs on local machines (i.e., the computers used directly by users) and handles all access to the graphics cards, display screens and input devices (typically a keyboard and mouse) on those computers.

More info here.

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

You can use npm link to create a symbolic link to your global package in your projects folder.

Example:

$ npm install -g express
$ cd [local path]/project
$ npm link express

All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')

Invariant Violation: Objects are not valid as a React child

I just got the same error but due to a different mistake: I used double braces like:

{{count}}

to insert the value of count instead of the correct:

{count}

which the compiler presumably turned into {{count: count}}, i.e. trying to insert an Object as a React child.

How to add "required" attribute to mvc razor viewmodel text input editor

A newer way to do this in .NET Core is with TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Building on these examples (MaxLength, Label), you can extend the existing TagHelper to suit your needs.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

You'll then need to add it to be used in your views:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Given the following model:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

and view (snippet):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

Will result in this HTML:

<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

I hope this is helpful to anyone with same question but using .NET Core.

Has an event handler already been added?

This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.

public class MyClass
{
  event Action MyEvent;
}

...

MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;

...

Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example

Console.WriteLine(handlers[0].Method.Name);//prints the name of the method

You can examine various properties on the Method property of the delegate to see if a specific function has been added.

If you are looking to see if there is just one attached, you can just test for null.

Inner join vs Where

They're logically identical, but in the earlier versions of Oracle that adopted ANSI syntax there were often bugs with it in more complex cases, so you'll sometimes encounter resistance from Oracle developers when using it.

How to wait for async method to complete?

Actually I found this more helpful for functions that return IAsyncAction.

            var task = asyncFunction();
            while (task.Status == AsyncStatus.Completed) ;

Comparing two integer arrays in Java

Even though there is something easy like .equals, I'd like to point out TWO mistakes you made in your code. The first: when you go through the arrays, you say b is true or false. Then you start again to check, because of the for-loop. But each time you are giving b a value. So, no matter what happens, the value b gets set to is always the value of the LAST for-loop. Next time, set boolean b = true, if equal = true, do nothing, if equal = false, b=false.

Secondly, you are now checking each value in array1 with each value in array2. If I understand correctly, you only need to check the values at the same location in the array, meaning you should have deleted the second for-loop and check like this: if (array2[i] == array1[i]). Then your code should function as well.

Your code would work like this:

public static void compareArrays(int[] array1, int[] array2) {
    boolean b = true;
    for (int i = 0; i < array2.length; i++) {
        if (array2[i] == array1[i]) {
            System.out.println("true");
        } else {
            b = false;
            System.out.println("False");
        }
    } 
    return b;

}

But as said by other, easier would be: Arrays.equals(ary1,ary2);

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

How do I connect to mongodb with node.js (and authenticate)?

Slight typo with Chris' answer.

Db.authenticate(user, password, function({ // callback }));

should be

Db.authenticate(user, password, function(){ // callback } );

Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.

How do I read text from the clipboard?

Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).

See sample here: http://code.activestate.com/recipes/474121/

How do I convert strings in a Pandas data frame to a 'date' data type?

I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read:

dfcsv = pd.read_csv('xyz.csv', parse_dates=[0]) where the 0 refers to the column the date is in.
You could also add , index_col=0 in there if you want the date to be your index.

See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

JSON Array iteration in Android/Java

When I tried @vipw's suggestion, I was faced with this exception: The method getJSONObject(int) is undefined for the type JSONArray

This worked for me instead:

int myJsonArraySize = myJsonArray.size();

for (int i = 0; i < myJsonArraySize; i++) {
    JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);

    // Do whatever you have to do to myJsonObject...
}

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

What's the canonical way to check for type in Python?

To Hugo:

You probably mean list rather than array, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.

Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all

try:
   my_sequence.extend(o)
except TypeError:
  my_sequence.append(o)

One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.

I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ] around your single value when you pass it in if need be.

(Though this can cause errors with strings, as they do look like (are) sequences.)

window.location.href and window.open () methods in JavaScript

There are already answers which describes about window.location.href property and window.open() method.

I will go by Objective use:

1. To redirect the page to another

Use window.location.href. Set href property to the href of another page.

2. Open link in the new or specific window.

Use window.open(). Pass parameters as per your goal.

3. Know current address of the page

Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.

See Location Object for more information.

A quick and easy way to join array elements with a separator (the opposite of split) in Java

Using Java 8 you can do this in a very clean way:

String.join(delimiter, elements);

This works in three ways:

1) directly specifying the elements

String joined1 = String.join(",", "a", "b", "c");

2) using arrays

String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);

3) using iterables

List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

Using Jquery Datatable with AngularJs

After many hours of experimenting with using jQueryDataTables with Angular, I found what I needed was available with a native Angular directive called ng-table. It provides sorting, pagination, and ajax reloads (sort of lazy loading capable with a few tweaks).

Specific Time Range Query in SQL Server

I (using PostgrSQL on PGadmin4) queried for results that are after or on 21st Nov 2017 at noon, like this (considering the display format of hours on my database):

select * from Table1 where FIELD >='2017-11-21 12:00:00' 

Concatenating multiple text files into a single file in Bash

You can use Windows shell copy to concatenate files.

C:\> copy *.txt outputfile

From the help:

To append files, specify a single file for destination, but multiple files for source (using wildcards or file1+file2+file3 format).

Label on the left side instead above an input field

You can use a span tag inside the label

  <div class="form-group">
    <label for="rg-from">
      <span>Ab:</span> 
      <input type="text" id="rg-from" name="rg-from" value="" class="form-control">
    </label>
  </div>

Best way to define private methods for a class in Objective-C

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.

Flash CS4 refuses to let go

Try deleting your ASO files.

ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.

This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.

ComboBox.SelectedText doesn't give me the SelectedText

I think you want to use

String status = "The status of my combobox is " + comboBoxTest.Text

SelectedText property from MSDN

Gets or sets the text that is selected in the editable portion of a ComboBox.

while Text property from MSDN

Gets or sets the text associated with this control.

Convert Json Array to normal Java list

_x000D_
_x000D_
   private String[] getStringArray(JSONArray jsonArray) throws JSONException {_x000D_
            if (jsonArray != null) {_x000D_
                String[] stringsArray = new String[jsonArray.length()];_x000D_
                for (int i = 0; i < jsonArray.length(); i++) {_x000D_
                    stringsArray[i] = jsonArray.getString(i);_x000D_
                }_x000D_
                return stringsArray;_x000D_
            } else_x000D_
                return null;_x000D_
        }
_x000D_
_x000D_
_x000D_

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Disable firefox same origin policy

As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases

In the options panel you can configure which header to inject and specific website to have it enabled automatically.

enter image description here

cmake - find_library - custom library location

I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in

CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake

(which can be set through an environment variable). So for example the boost configuration is in the path

CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake

In that configuration you can set variables. My config file for boost looks like that:

set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS}) 
    set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
    set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )

Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.

Hope this this is helpful for other people.

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

Disable / Check for Mock Location (prevent gps spoofing)

I have done some investigation and sharing my results here,this may be useful for others.

First, we can check whether MockSetting option is turned ON

public static boolean isMockSettingsON(Context context) {
    // returns true if mock location enabled, false if not enabled.
    if (Settings.Secure.getString(context.getContentResolver(),
                                Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
        return false;
    else
        return true;
}

Second, we can check whether are there other apps in the device, which are using android.permission.ACCESS_MOCK_LOCATION (Location Spoofing Apps)

public static boolean areThereMockPermissionApps(Context context) {
    int count = 0;

    PackageManager pm = context.getPackageManager();
    List<ApplicationInfo> packages =
        pm.getInstalledApplications(PackageManager.GET_META_DATA);

    for (ApplicationInfo applicationInfo : packages) {
        try {
            PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
                                                        PackageManager.GET_PERMISSIONS);

            // Get Permissions
            String[] requestedPermissions = packageInfo.requestedPermissions;

            if (requestedPermissions != null) {
                for (int i = 0; i < requestedPermissions.length; i++) {
                    if (requestedPermissions[i]
                        .equals("android.permission.ACCESS_MOCK_LOCATION")
                        && !applicationInfo.packageName.equals(context.getPackageName())) {
                        count++;
                    }
                }
            }
        } catch (NameNotFoundException e) {
            Log.e("Got exception " , e.getMessage());
        }
    }

    if (count > 0)
        return true;
    return false;
}

If both above methods, first and second are true, then there are good chances that location may be spoofed or fake.

Now, spoofing can be avoided by using Location Manager's API.

We can remove the test provider before requesting the location updates from both the providers (Network and GPS)

LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);

try {
    Log.d(TAG ,"Removing Test providers")
    lm.removeTestProvider(LocationManager.GPS_PROVIDER);
} catch (IllegalArgumentException error) {
    Log.d(TAG,"Got exception in removing test  provider");
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);

I have seen that removeTestProvider(~) works very well over Jelly Bean and onwards version. This API appeared to be unreliable till Ice Cream Sandwich.

Flutter Update: Use Geolocator and check Position object's isMocked property.

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

How to get first and last day of week in Oracle?

Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.

Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.

create table calender(
   day           date      not null -- Truncated date
  ,iso_year_week number(6) not null -- ISO Year week  (IYYYIW)
  ,retail_week   number(6) not null -- Monday to Sunday (YYYYWW)
  ,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
  ,primary key(day)
);

You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:

select a.colA
      ,a.colB
      ,b.first_day
      ,b.last_day
  from your_table_with_weeks a
  join (select iso_year_week
              ,min(day) as first_day
              ,max(day) as last_day
          from calendar
         group  
            by iso_year_week
       ) b on(a.iso_year_week = b.iso_year_week)

If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.

Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char())) function calls.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

this is probably about you don't entered correct dependency version. you can select correct dependency from this:

file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK

if cannot find your needs you should update your sdk from below way:

tools>android>sdk manager>sdk update>select any thing you need>ok

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

Can a background image be larger than the div itself?

Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.

You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.

How to check which locks are held on a table

I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.

(MUST switch to the Database you want to observe to get object_id)

SELECT 
     TL.resource_type,
     TL.resource_database_id,
     TL.resource_associated_entity_id,
     TL.request_mode,
     TL.request_session_id,
     WT.blocking_session_id,
     O.name AS [object name],
     O.type_desc AS [object descr],
     P.partition_id AS [partition id],
     P.rows AS [partition/page rows],
     AU.type_desc AS [index descr],
     AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT 
 ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O 
 ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P 
 ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU 
 ON AU.allocation_unit_id = TL.resource_associated_entity_id;

How do I access command line arguments in Python?

Python code:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

Invocation:

$python myfile.py var1 var2 var3

Output:

Params= var1 var2 var3 

How can I transform string to UTF-8 in C#?

If you want to save any string to mysql database do this:->

Your database field structure i phpmyadmin [ or any other control panel] should set to utf8-gerneral-ci

2) you should change your string [Ex. textbox1.text] to byte, therefor

2-1) define byte[] st2;

2-2) convert your string [textbox1.text] to unicode [ mmultibyte string] by :

byte[] st2 = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);

3) execute this sql command before any query:

string mysql_query2 = "SET NAMES 'utf8'";
cmd.CommandText = mysql_query2;
cmd.ExecuteNonQuery();

3-2) now you should insert this value in to for example name field by :

cmd.CommandText = "INSERT INTO customer (`name`) values (@name)";

4) the main job that many solution didn't attention to it is the below line: you should use addwithvalue instead of add in command parameter like below:

cmd.Parameters.AddWithValue("@name",ut);

++++++++++++++++++++++++++++++++++ enjoy real data in your database server instead of ????

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

Vue.js data-bind style backgroundImage not working

Based on my knowledge, if you put your image folder in your public folder, you can just do the following:

   <div :style="{backgroundImage: `url(${project.imagePath})`}"></div>

If you put your images in the src/assets/, you need to use require. Like this:

   <div :style="{backgroundImage: 'url('+require('@/assets/'+project.image)+')'}">. 
   </div>

One important thing is that you cannot use an expression that contains the full URL like this project.image = '@/assets/image.png'. You need to hardcode the '@assets/' part. That was what I've found. I think the reason is that in Webpack, a context is created if your require contains expressions, so the exact module is not known on compile time. Instead, it will search for everything in the @/assets folder. More info could be found here. Here is another doc explains how the Vue loader treats the link in single file components.

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

How do I read a text file of about 2 GB?

EmEditor works quite well for me. It's shareware IIRC but doesn't stop working after the license expires..

Keep background image fixed during scroll using css

Just add background-attachment to your code

body {
    background-position: center;
    background-image: url(../images/images5.jpg);
    background-attachment: fixed;
}

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

Android - Get value from HashMap

HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("Color1", "Red");
meMap.put("Color2", "Blue");
meMap.put("Color3", "Green");
meMap.put("Color4", "White");

Iterator myVeryOwnIterator = meMap.values().iterator();
while(myVeryOwnIterator.hasNext()) {
    Toast.makeText(getBaseContext(), myVeryOwnIterator.next(), Toast.LENGTH_SHORT).show();
}

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

Convert regular Python string to raw string

Since strings in Python are immutable, you cannot "make it" anything different. You can however, create a new raw string from s, like this:

raw_s = r'{}'.format(s)

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's the ternary or conditional operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse

Where the values will only be evaluated if they are chosen.

Initializing an Array of Structs in C#

Are you using C# 3.0? You can use object initializers like so:

static MyStruct[] myArray = 
            new MyStruct[]{
                new MyStruct() { id = 1, label = "1" },
                new MyStruct() { id = 2, label = "2" },
                new MyStruct() { id = 3, label = "3" }
            };

How to create an 2D ArrayList in java?

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList

Converting two lists into a matrix

Simple you can try this

a=list(zip(portfolio, index))

How can I get the list of files in a directory using C or C++?

GNU Manual FTW

http://www.gnu.org/software/libc/manual/html_node/Simple-Directory-Lister.html#Simple-Directory-Lister

Also, sometimes it's good to go right to the source (pun intended). You can learn a lot by looking at the innards of some of the most common commands in Linux. I've set up a simple mirror of GNU's coreutils on github (for reading).

https://github.com/homer6/gnu_coreutils/blob/master/src/ls.c

Maybe this doesn't address Windows, but a number of cases of using Unix variants can be had by using these methods.

Hope that helps...

Need to find element in selenium by css

You can describe your css selection like cascading style sheet dows:

protected override void When()
{
   SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}

How to add Class in <li> using wp_nav_menu() in Wordpress?

None of these responses really seem to answer the question. Here's something similar to what I'm utilizing on a site of mine by targeting a menu item by its title/name:

function add_class_to_menu_item($sorted_menu_objects, $args) {
    $theme_location = 'primary_menu';  // Name, ID, or Slug of the target menu location
    $target_menu_title = 'Link';  // Name/Title of the menu item you want to target
    $class_to_add = 'my_own_class';  // Class you want to add

    if ($args->theme_location == $theme_location) {
        foreach ($sorted_menu_objects as $key => $menu_object) {
            if ($menu_object->title == $target_menu_title) {
                $menu_object->classes[] = $class_to_add;
                break; // Optional.  Leave if you're only targeting one specific menu item
            }
        }
    }

    return $sorted_menu_objects;
}
add_filter('wp_nav_menu_objects', 'add_class_to_menu_item', 10, 2);

Creating a LinkedList class from scratch

How have I created a linkedlist like this. How does this work? This is all a linked list is. An item with a link to the next item in the list. As long as you keep a reference to the item at the beginning of the list, you can traverse the whole thing using each subsequent reference to the next value.

To append, all you need to do is find the end of the list, and make the next item the value you want appended, so if this has non-null next, you would have to call append on the next item until you find the end of the list.

this.next.Append(word);

Laravel 5 call a model function in a blade view

I solve the problem. So simple. Syntax error.

  • App\Product
  • App\Service

enter image description here

But I also want to know how to pass a function with parameters to view....

How to disable horizontal scrolling of UIScrollView?

Use this single line.

self.automaticallyAdjustsScrollViewInsets = NO;

Collision Detection between two images in Java

Since Java doesn't have an intersect function (really!?) you can do collision detection by simply comparying the X and Y, Width and Height values of the bounding boxes (rectangle) for each of the objects that could potentially collide.

So... in the base object of each colliding object... i.e. if your player and enemy have a common base you can put a simple Rectangle object called something like BoundingBox. If the common base is a built in Java class then you'll need to create a class that extends the build in class and have the player and enemy objects extend your new class or are instances of that class.

At creation (and each tick or update) you'll need to set the BoundingBox paremeters for both your player and enemy. I don't have the Rectangle class infront of me but its most likely something like X, Y, Width and finally Height. X and Y are that objects location in your game world. The width and height are self explanatory I think. They'll most likely come out from the right of the players location though so, if the X and Y were bothe at 0 and your Width and Height were both at 256 you wouldn't see anything because the character would be at the top left outside of the screen.

Anyways... to detect a collision, you'll want to compare the attributes of the player and enemy BoundingBoxes. So something like this...

 if( Player.BoundingBox.X = Enemy.BoundingBox.X && If( Player.BoundingBox.Y = Enemy.BoundingBox.Y )
 {
      //Oh noes!  The enemy and player are on top of eachother.
 }

The logic can get sort of complicated but you'll need to compare the distances between each BoundingBox and compare locations.

python - if not in list

You better do this syntax

if not (item in mylist):  
    Code inside the if

In bash, how to store a return value in a variable?

The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.

To return information, like your number, use

echo "$value"

To print additional information that you don't want captured, use

echo "my irrelevant info" >&2 

Finally, to capture it, use what you did:

 result=$(password_formula)

In other words:

echo "enter: "
        read input

password_formula()
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        echo $second >&2
        echo $sum >&2

        if [ $sum -gt 9 ]
        then
               sum=${sum:1}
        fi

        value=$second$sum$first
        echo $value
}
result=$(password_formula)
echo "The value is $result"

How to change the JDK for a Jenkins job?

Using latest Jenkins version 2.7.4 which is also having a bug for existing jobs.

  1. Add new JDKs through Manage Jenkins -> Global Tool Configuration -> JDK ** If you edit current job then JDK dropdown is not showing (bug)

  2. Hit http://your_jenkin_server:8080/restart and restart the server

  3. Re-configure job

Now, you should see JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

How does java do modulus calculations with negative numbers?

The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of

-13 % 64

the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51 -13 - (-64) = -13 + 64 = 51

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

Best data type for storing currency values in a MySQL database

It is also important to work out how many decimal places maybe required for your calculations.

I worked on a share price application that required the calculation of the price of one million shares. The quoted share price had to be stored to 7 digits of accuracy.

jQuery - keydown / keypress /keyup ENTERKEY detection?

update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which/event.keyCode and start using event.key:

if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")

Table scroll with HTML and CSS

Late answer, another idea, but very short.

  1. put the contents of header cells into div
  2. fix the header contents, see CSS
table  { margin-top:  20px; display: inline-block; overflow: auto; }
th div { margin-top: -20px; position: absolute; }

Note that it is possible to display table as inline-block due to anonymous table objects:

"missing" [in HTML table tree structure] elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself.

_x000D_
_x000D_
/* scrolltable rules */_x000D_
table  { margin-top:  20px; display: inline-block; overflow: auto; }_x000D_
th div { margin-top: -20px; position: absolute; }_x000D_
_x000D_
/* design */_x000D_
table { border-collapse: collapse; }_x000D_
tr:nth-child(even) { background: #EEE; }
_x000D_
<table style="height: 150px">_x000D_
  <tr> <th><div>first</div> <th><div>second</div>_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo foo foo foo foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar bar bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
</table>
_x000D_
_x000D_
_x000D_

import an array in python

In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:

import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))

This prints:

z is: ['grape', 'cherry', 'mango']

Which is stored on disk as the filename: outfile.dat.npy

The important methods here are the tolist() and np.array(...) conversion functions.

php variable in html no other way than: <?php echo $var; ?>

I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.

Personally I don't mind mixing HTML and PHP like so

<a href="<?php echo $link;?>">link description</a>

As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.

echo '<a href="'.$link.'">link description</a>';

The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

How to use if statements in underscore.js templates?

From here:

"You can also refer to the properties of the data object via that object, instead of accessing them as variables." Meaning that for OP's case this will work (with a significantly smaller change than other possible solutions):

<% if (obj.date) { %><span class="date"><%= date %></span><% }  %>

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

PHP - check if variable is undefined

An another way is simply :

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Will return :

"Yes 3"

The best way is to use isset(), otherwise you can have an error like "undefined $test".

You can do it like this :

if( isset($test) && ($test!==null) )

You'll not have any error because the first condition isn't accepted.

Maven fails to find local artifact

check if if your artifact Y have packaging set to "jar". If you have defined it as "war" by error or copy paste, it will show this strange "was cached in the local repository, resolution will not be reattempted until the update interval of internal has elapsed or updates are forced". I would expect something like "artifact Y is war, jar type expected".

How can I install Visual Studio Code extensions offline?

As of today the download URL for the latest version of the extension is embedded verbatim in the source of the page on Marketplace, e.g. source at URL:

https://marketplace.visualstudio.com/items?itemName=lukasz-wronski.ftp-sync

contains string:

https://lukasz-wronski.gallerycdn.vsassets.io/extensions/lukasz-wronski/ftp-sync/0.3.3/1492669004156/Microsoft.VisualStudio.Services.VSIXPackage

I use following Python regexp to extract dl URL:

urlre = re.search(r'source.+(http.+Microsoft\.VisualStudio\.Services\.VSIXPackage)', content)
if urlre:
    return urlre.group(1)

Mark error in form using Bootstrap

One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.

<span class="error text-danger">Some Errors related to something</span>

Output looks like something below:

Example of error text in modal

Create directory if it does not exist

I had the exact same problem. You can use something like this:

$local = Get-Location;
$final_local = "C:\Processing";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        mkdir $final_local;
        cd $final_local;
        liga;
    }

    ## If path already exists
    ## DB Connect
    elseif ((Test-Path $final_local) -eq 1)
    {
        cd $final_local;
        echo $final_local;
        liga;  (function created by you TODO something)
    }
}

Should try...catch go inside or outside a loop?

put it inside. You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw. Think about what would be interesting to you in the debugger at this point in the program.

Consider:

try {
   // parse
} catch (NumberFormatException nfe){
   throw new RuntimeException("Could not parse as a Float: [" + myString + 
                              "] found at index: " + i, nfe);
} 

In the time of need you will really appreciate an exception like this with as much information in it as possible.

Controlling Spacing Between Table Cells

table.test td {
    background-color: lime;
    padding: 12px;
    border:2px solid #fff;border-collapse:separate;
}

Convert char * to LPWSTR

I'm using the following in VC++ and it works like a charm for me.

CA2CT(charText)

Is it possible to run selenium (Firefox) web driver without a GUI?

UPDATE: You do not need XVFB to run headless Firefox anymore. Firefox v55+ on Linux and Firefox v56+ on Windows/Mac now supports headless execution.

I added some how-to-use documentation here:

https://developer.mozilla.org/en-US/Firefox/Headless_mode#Selenium_in_Java

Download file from an ASP.NET Web API method using AngularJS

For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js

Web API

module Api
  module V1
    class DownloadsController < BaseController

      def show
        @download = Download.find(params[:id])
        send_data @download.blob_data
      end
    end
  end
end

HTML

 <a ng-click="download('foo')">download presentation</a>

Angular controller

 $scope.download = function(type) {
    return Download.get(type);
  };

Angular Service

'use strict';

app.service('Download', function Download(Restangular) {

  this.get = function(id) {
    return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
      console.log(data)
      var blob = new Blob([data], {
        type: "application/pdf"
      });
      //saveAs provided by FileSaver.js
      saveAs(blob, id + '.pdf');
    })
  }
});

Are loops really faster in reverse?

I want to contribute to this thread the fastest loop in JavaScript that is cross-browser ! This loop yields over 500% improvement compared to the reverse while loop.

My Blog: Fastest Loop in JavaScript

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

Can't specify the 'async' modifier on the 'Main' method of a console app

I'll add an important feature that all of the other answers have overlooked: cancellation.

One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:

static void Main(string[] args)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    
    System.Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
    };

    MainAsync(args, cts.Token).GetAwaiter.GetResult();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    ...
}

How to fix "ImportError: No module named ..." error in Python?

Here is a step-by-step solution:

  1. Add a script called run.py in /home/bodacydo/work/project and edit it like this:

    import programs.my_python_program
    programs.my_python_program.main()
    

    (replace main() with your equivalent method in my_python_program.)

  2. Go to /home/bodacydo/work/project
  3. Run run.py

Explanation: Since python appends to PYTHONPATH the path of the script from which it runs, running run.py will append /home/bodacydo/work/project. And voilà, import foo.tasks will be found.

What is Options +FollowSymLinks?

You might try searching the internet for ".htaccess Options not allowed here".

A suggestion I found (using google) is:

Check to make sure that your httpd.conf file has AllowOverride All.

A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):

# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html

# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

Cannot find R.layout.activity_main

You're importing invalid R class, check imports.

Get the value in an input text box

//Get
var bla = $('#txt_name').val();

//Set
$('#txt_name').val(bla);

Ignoring directories in Git repositories on Windows

I had some issues creating a file in Windows Explorer with a . at the beginning.

A workaround was to go into the commandshell and create a new file using "edit".

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

How can I style a PHP echo text?

Store your results in variables, and use them in your HTML and add the necessary styling.

$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];

And in the HTML, you could do:

<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>

Now, you can simply add the styles for country class in your CSS, like so:

#userdetails {

/* styles go here */

}

Alternatively, you could also use this in your HTML:

<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>

Hope this helps!

Using Java to find substring of a bigger string using Regular Expression

String input = "FOO[BAR]";
String result = input.substring(input.indexOf("[")+1,input.lastIndexOf("]"));

This will return the value between first '[' and last ']'

Foo[Bar] => Bar

Foo[Bar[test]] => Bar[test]

Note: You should add error checking if the input string is not well formed.

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

Server Client send/receive simple text

bool SendReceiveTCP(string ipAddress, string sendMsg, ref string recMsg)
    {
        try
        {
            DateTime startTime=new DateTime();
            TcpClient clt = new TcpClient();
            clt.Connect(ipAddress, 8001);
            NetworkStream nts = clt.GetStream();
            nts.Write(Encoding.ASCII.GetBytes(sendMsg),0, sendMsg.Length);
            startTime = DateTime.Now;
            while (true)
            {
                if (nts.DataAvailable)
                {
                    byte[] tmpBuff = new byte[1024];
                    System.Threading.Thread.Sleep(100);
                    int readOut=nts.Read(tmpBuff, 0, 1024);
                    if (readOut > 0)
                    {
                        recMsg = Encoding.ASCII.GetString(tmpBuff, 0, readOut);
                        nts.Close();
                        clt.Close();
                        return true;
                    }
                    else
                    {
                        nts.Close();
                        clt.Close();
                        return false;
                    }
                }
                TimeSpan tps = DateTime.Now - startTime;
                if (tps.TotalMilliseconds > 2000)
                {
                    nts.Close();
                    clt.Close();
                    return false;
                }
                System.Threading.Thread.Sleep(50);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

jQuery SVG, why can't I addClass?

I use Snap.svg to add a class to and SVG.

var jimmy = Snap(" .jimmy ")

jimmy.addClass("exampleClass");

http://snapsvg.io/docs/#Element.addClass

How to replace sql field value

It depends on what you need to do. You can use replace since you want to replace the value:

select replace(email, '.com', '.org')
from yourtable

Then to UPDATE your table with the new ending, then you would use:

update yourtable
set email = replace(email, '.com', '.org')

You can also expand on this by checking the last 4 characters of the email value:

update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'

However, the issue with replace() is that .com can be will in other locations in the email not just the last one. So you might want to use substring() the following way:

update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';

See SQL Fiddle with Demo

Using substring() will return the start of the email value, without the final .com and then you concatenate the .org to the end. This prevents the replacement of .com elsewhere in the string.

Alternatively you could use stuff(), which allows you to do both deleting and inserting at the same time:

update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';

This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com) and insert .org instead.

See SQL Fiddle with Demo for this method as well.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

How to focus on a form input text field on page load using jQuery?

This is what I prefer to use:

<script type="text/javascript">
    $(document).ready(function () {
        $("#fieldID").focus(); 
    });
</script>

How can I have grep not print out 'No such file or directory' errors?

I usually don't let grep do the recursion itself. There are usually a few directories you want to skip (.git, .svn...)

You can do clever aliases with stances like that one:

find . \( -name .svn -o -name .git \) -prune -o -type f -exec grep -Hn pattern {} \;

It may seem overkill at first glance, but when you need to filter out some patterns it is quite handy.

How do servlets work? Instantiation, sessions, shared variables and multithreading

ServletContext

When the servlet container (like Apache Tomcat) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server's memory. The web app's web.xml and all of included web-fragment.xml files is parsed, and each <servlet>, <filter> and <listener> found (or each class annotated with @WebServlet, @WebFilter and @WebListener respectively) is instantiated once and kept in the server's memory as well. For each instantiated filter, its init() method is invoked with a new FilterConfig.

When a Servlet has a <servlet><load-on-startup> or @WebServlet(loadOnStartup) value greater than 0, then its init() method is also invoked during startup with a new ServletConfig. Those servlets are initialized in the same order specified by that value (1 is 1st, 2 is 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the same order as they appear in the web.xml, web-fragment.xml, or @WebServlet classloading. In the event the "load-on-startup" value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.

When the servlet container is finished with all of the above described initialization steps, then the ServletContextListener#contextInitialized() will be invoked.

When the servlet container shuts down, it unloads all web applications, invokes the destroy() method of all its initialized servlets and filters, and all ServletContext, Servlet, Filter and Listener instances are trashed. Finally the ServletContextListener#contextDestroyed() will be invoked.

HttpServletRequest and HttpServletResponse

The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (e.g. user with a web browser, or programmatically using URLConnection) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter in the chain and, eventually, the Servlet instance.

In the case of filters, the doFilter() method is invoked. When the servlet container's code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.

In the case of servlets, the service() method is invoked. By default, this method determines which one of the doXxx() methods to invoke based off of request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.

The request object provides access to all of the information about the HTTP request, such as its URL, headers, query string and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made available for reuse.

HttpSession

When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and stores it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.

As per the HTTP cookie specification (a contract any decent web browser and web server must adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.

The HttpSession stays alive until it has been idle (i.e. not used in a request) for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.

On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HttpSession to be created, with an entirely new session cookie being used.

In a nutshell

  • The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.
  • The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among all requests in the same session.
  • The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is not shared elsewhere.
  • All Servlet, Filter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.
  • Any attribute that is defined in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an attribute of its closest matching scope.

Thread Safety

That said, your major concern is possibly thread safety. You should now know that servlets and filters are shared among all requests. That's the nice thing about Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, init() and destroy() them for every single request.

You should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's not thread-safe! The below example illustrates this:

public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

See also:

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

How do I alter the precision of a decimal column in Sql Server?

Go to enterprise manager, design table, click on your field.

Make a decimal column

In the properties at the bottom there is a precision property

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

If you know the the name of the file and if you always want to download that specific file, then you can easily get the ID and other attributes for your desired file from: https://developers.google.com/drive/v2/reference/files/list (towards the bottom you will find a way to run queries). In the q field enter title = 'your_file_name' and run it. You should see some result show up right below and within it should be an "id" field. That is the id you are looking for.

You can also play around with additional parameters from: https://developers.google.com/drive/search-parameters

How can I search (case-insensitive) in a column using LIKE wildcard?

I've always solved this using lower:

SELECT * FROM trees WHERE LOWER( trees.title ) LIKE  '%elm%'

How do I do a multi-line string in node.js?

Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.

CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.

I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.

If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.

Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".

How do I get console input in javascript?

Good old readline();.

See MDN (archive).

Stretch background image css?

CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

.style1 {
  ...
  background-size: 100%;
}

You can specify just width or height with:

background-size: 100% 50%;

Which will stretch it 100% of the width and 50% of the height.


Browser support: http://caniuse.com/#feat=background-img-opts

Using CMake with GNU Make: How can I see the exact commands?

It is convenient to set the option in the CMakeLists.txt file as:

set(CMAKE_VERBOSE_MAKEFILE ON)

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

How to strip HTML tags with jQuery?

If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:

$(".contentToStrip").each(function(){
  $(this).replaceWith($(this).html());
});

Getting Google+ profile picture url with user_id

trying to access the /s2/profile/photo url works for most users but not all.

The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:

  1. Get a Google+ API key on https://cloud.google.com/console

  2. Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=

Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +

  1. you will get a very comprehensive JSON representation of the profile data which includes: "image":{"url": "https://lh4.googleusercontent.com/..... the rest of the picture url...."}

Set the maximum character length of a UITextField

for Swift 3.1 or later

firstly add protocol UITextFieldDelegate

like:-

class PinCodeViewController: UIViewController, UITextFieldDelegate { 
.....
.....
.....

}

after that create your UITextField and set delegate

Complete Exp: -

import UIKit

class PinCodeViewController: UIViewController, UITextFieldDelegate {

let pinCodetextField: UITextField = {
    let tf = UITextField()
    tf.placeholder = "please enter your pincode"
    tf.font = UIFont.systemFont(ofSize: 15)
    tf.borderStyle = UITextBorderStyle.roundedRect
    tf.autocorrectionType = UITextAutocorrectionType.no
    tf.keyboardType = UIKeyboardType.numberPad
    tf.clearButtonMode = UITextFieldViewMode.whileEditing;
    tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
 return tf
  }()


 override func viewDidLoad() {
   super.viewDidLoad()
   view.addSubview(pinCodetextField)
    //----- setup your textfield anchor or position where you want to show it----- 


    // after that 
pinCodetextField.delegate = self // setting the delegate

 }
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return !(textField.text?.characters.count == 6 && string != "")
     } // this is return the maximum characters in textfield 
    }

git: patch does not apply

Try using the solution suggested here: https://www.drupal.org/node/1129120

patch -p1 < example.patch

This helped me .

Insert image after each list item

I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:

ul li:after {
    content: url('../images/small_triangle.png');
}

Programmatically scroll to a specific position in an Android ListView

For a SmoothScroll with Scroll duration:

getListView().smoothScrollToPositionFromTop(position,offset,duration);

Parameters
position -> Position to scroll to
offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished
duration-> Number of milliseconds to use for the scroll

Note: From API 11.

HandlerExploit's answer was what I was looking for, but My listview is quite lengthy and also with alphabet scroller. Then I found that the same function can take other parameters as well :)


Edit:(From AFDs suggestion)

To position the current selection:

int h1 = mListView.getHeight();
int h2 = listViewRow.getHeight();

mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);  

How can I list ALL grants a user received?

The most comprehensive and reliable method I know is still by using DBMS_METADATA:

select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'OBJECT_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', :username ) from dual;

(username must be written all uppercase)

Interesting answers though.

smtpclient " failure sending mail"

Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress out of the loop which you are using for sending mails. The fromaddress field is getting assigned again and again in the loop that is your problem.

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

What should be in my .gitignore for an Android Studio project?

Updated 7/2015:

Here is the definitive source from JetBrains


Directory based project format (.idea directory)

This format is used by all the recent IDE versions by default. Here is what you need to share:

  • All the files under .idea directory in the project root except the workspace.xml and tasks.xml files which store user specific settings
  • All the .iml module files that can be located in different module directories (applies to IntelliJ IDEA)

Be careful about sharing the following:

  • Android artifacts that produce a signed build (will contain keystore passwords)
  • In IDEA 13 and earlier dataSources.ids, datasources.xml can contain database passwords. IDEA 14 solves this problem.

You may consider not to share the following:

  • gradle.xml file, see this discussion
  • user dictionaries folder (to avoid conflicts if other developer has the same name)
  • XML files under .idea/libraries in case they are generated from Gradle project

Legacy project format (.ipr/.iml/.iws files)

  • Share the project .ipr file and all the .iml module files, don't share the .iws file as it stores user specific settings

While these instructions are for IntelliJ IDEA, they hold true 100% for Android Studio.


Here is a .gitignore snippet that incorporates all of the above rules:

# Android Studio / IntelliJ IDEA 
*.iws
.idea/libraries
.idea/tasks.xml
.idea/vcs.xml
.idea/workspace.xml

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I also tried http://www.eclipse.org/cdt/ in Ubuntu 12.04.2 LTS and works fine!

  1. First, I downloaded it from www.eclipse.org/downloads/, choosing Eclipse IDE for C/C++ Developers.
  2. I save the file somewhere, let´s say into my home directory. Open a console or terminal, and type:

    >>cd ~; tar xvzf eclipse*.tar.gz;

  3. Remember for having Eclipse running in Linux, it is required a JVM, so download a jdk file e.g jdk-7u17-linux-i586.rpm (I cann´t post the link due to my low reputation) ... anyway

  4. Install the .rpm file following http://www.wikihow.com/Install-Java-on-Linux

  5. Find the path to the Java installation, by typing:

    >>which java

  6. I got /usr/bin/java. To start up Eclipse, type:

    >>cd ~/eclipse; ./eclipse -vm /usr/bin/java

Also, once everything is installed, in the home directory, you can double-click the executable icon called eclipse, and then you´ll have it!. In case you like an icon, create a .desktop file in /usr/share/applications:

>>sudo gedit /usr/share/applications/eclipse.desktop

The .desktop file content is as follows:

[Desktop Entry]  
Name=Eclipse  
Type=Application  
Exec="This is the path of the eclipse executable on your machine"  
Terminal=false 
Icon="This is the path of the icon.xpm file on your machine"  
Comment=Integrated Development Environment  
NoDisplay=false  
Categories=Development;IDE  
Name[en]=eclipse.desktop  

Best luck!

Return multiple values from a SQL Server function

Erland Sommarskog has an exhaustive post about passing data in SQL Server located here:

http://www.sommarskog.se/share_data.html

He covers SQL Server 2000, 2005, and 2008, and it should probably be read in its full detail as there is ample coverage of each method's advantages and drawbacks. However, here are the highlights of the article (frozen in time as of July 2015) for the sake of providing search terms that can be used to look greater details:

This article tackles two related questions:

  • How can I use the result set from one stored procedure in another, also expressed as How can I use the result set from a stored
    procedure in a SELECT statement?
  • How can I pass a table data in a parameter from one stored procedure to another?

OUTPUT Parameters

  • Not generally applicable, but sometimes overlooked.

Table-valued Functions

  • Often the best choice for output-only, but there are several restrictions.
  • Examples:
    • Inline Functions: Use this to reuse a single SELECT.
    • Multi-statement Functions: When you need to encapsulate more complex logic.

Using a Table

  • The most general solution. My favoured choice for input/output scenarios.
  • Examples:
    • Sharing a Temp Table: Mainly for a single pair of caller/callee.
    • Process-keyed Table: Best choice for many callers to the same callee.
    • Global Temp Tables: A variation of process-keyed.

Table-valued Parameters

  • Req. Version: SQL 2008
  • Mainly useful when passing data from a client.

INSERT-EXEC

  • Deceivingly appealing, but should be used sparingly.

Using the CLR

  • Req. Version: SQL 2005
  • Complex, but useful as a last resort when INSERT-EXEC does not work.

OPENQUERY

  • Tricky with many pitfalls. Discouraged.

Using XML

  • Req. Version: SQL 2005
  • A bit of a kludge, but not without advantages.

Using Cursor Variables

  • Not recommendable.

Output first 100 characters in a string

From python tutorial:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So it is safe to use x[:100].

How do I close a tkinter window?

In case anyone wants to bind their Escape button to closing the entire GUI:

master = Tk()
master.title("Python")

def close(event):
    sys.exit()

master.bind('<Escape>',close)
master.mainloop()

PRINT statement in T-SQL

So, if you have a statement something like the following, you're saying that you get no 'print' result?

select * from sysobjects
PRINT 'Just selected * from sysobjects'

If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like

raiserror ('My Print Statement', 10,1) with nowait

This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

How do I find numeric columns in Pandas?

You can use the undocumented function _get_numeric_data() to filter only numeric columns:

df._get_numeric_data()

Example:

In [32]: data
Out[32]:
   A  B
0  1  s
1  2  s
2  3  s
3  4  s

In [33]: data._get_numeric_data()
Out[33]:
   A
0  1
1  2
2  3
3  4

Note that this is a "private method" (i.e., an implementation detail) and is subject to change or total removal in the future. Use with caution.

Selecting multiple columns with linq query and lambda expression

You can use:

public YourClass[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == 1)
                           .OrderBy(x => x.ID)
                           .Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
                           .ToArray();
        }
    }
    catch
    {
        return null;
    }
}

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

Summarizing multiple columns with dplyr?

All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather() from the tidyr package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by() and summarize() functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread() function.


library(tidyverse)

# Create reproducible df
set.seed(101)
df <- tibble(a   = sample(1:5, 10, replace=T), 
             b   = sample(1:5, 10, replace=T), 
             c   = sample(1:5, 10, replace=T), 
             d   = sample(1:5, 10, replace=T), 
             grp = sample(1:3, 10, replace=T))

# Convert to tidy format using gather
df %>%
    gather(key = variable, value = value, a:d) %>%
    group_by(grp, variable) %>%
    summarize(mean = mean(value)) %>%
    spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#> 
#>     grp        a     b        c        d
#> * <int>    <dbl> <dbl>    <dbl>    <dbl>
#> 1     1 3.000000   3.5 3.250000 3.250000
#> 2     2 1.666667   4.0 4.666667 2.666667
#> 3     3 3.333333   3.0 2.333333 2.333333

Is it possible to decrypt MD5 hashes?

No, he must have been confused about the MD5 dictionaries.

Cryptographic hashes (MD5, etc...) are one way and you can't get back to the original message with only the digest unless you have some other information about the original message, etc. that you shouldn't.

Pressed <button> selector

Maybe :active over :focus with :hover will help! Try

button {
background:lime;
}

button:hover {
background:green;
}

button:focus {
background:gray;
}

button:active {
background:red;
}

Then:

<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>

Then:

<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
 Sorry about that last one. :) I was just showing you a cool function! 
Wait... did I just emphasize a code block? This is cool!!!

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

No assembly found containing an OwinStartupAttribute Error

Add the following key in Web.config will remove the code

<appSettings>

  <add key="owin:AutomaticAppStartup" value="false" /> 
</appSettings>

How to force Chrome browser to reload .css file while debugging in Visual Studio?

I solved by this simple trick.

<script type="text/javascript">
  var style = 'assets/css/style.css?'+Math.random();;
</script>

<script type="text/javascript">
  document.write('<link href="'+style+'" rel="stylesheet">');
</script>

How can I make a countdown with NSTimer?

Add this to the end of your code... and call startTimer function with a parameter of where you want to count down to... For example (2 hours to the future of the date right now) -> startTimer(for: Date().addingTimeInterval(60*60*2))

Click here to view a screenshot of iPhone Simulator of how it'll look

extension ViewController
{
    func startTimer(for theDate: String)
    {
        let todaysDate = Date()
        let tripDate = Helper.getTripDate(forDate: theDate)
        let diffComponents = Calendar.current.dateComponents([.hour, .minute], from: Date(), to: tripDate)
        if let hours = diffComponents.hour
        {
            hoursLeft = hours
        }
        if let minutes = diffComponents.minute
        {
            minutesLeft = minutes
        }
        if tripDate > todaysDate
        {
            timer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
        }
        else
        {
            timerLabel.text = "00:00:00"
        }
    }
    
    @objc func onTimerFires()
    {
        secondsLeft -= 1
        
        //timerLabel.text = "\(hoursLeft):\(minutesLeft):\(secondsLeft)"
        timerLabel.text = String(format: "%02d:%02d:%02d", hoursLeft, minutesLeft, secondsLeft)
        if secondsLeft <= 0 {
            if minutesLeft != 0
            {
                secondsLeft = 59
                minutesLeft -= 1
            }
        }
        
        if minutesLeft <= 0 {
            if hoursLeft != 0
            {
                minutesLeft = 59
                hoursLeft -= 1
            }
        }
        
        if(hoursLeft == 0 && minutesLeft == 0 && secondsLeft == 0)
        {
            timer.invalidate()
        }
        
    }
}

How do I clear all options in a dropdown box?

This is a short way:

document.getElementById('mySelect').innerText = null;

One line, no for, no JQuery, simple.

What does the 'L' in front a string mean in C++?

It means the text is stored as wchar_t characters rather than plain old char characters.

(I originally said it meant unicode. I was wrong about that. But it can be used for unicode.)

Alternative to a goto statement in Java

The easiest is:

int label = 0;
loop:while(true) {
    switch(state) {
        case 0:
            // Some code
            state = 5;
            break;

        case 2:
            // Some code
            state = 4;
            break;
        ...
        default:
            break loop;
    }
}

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Illegal access: this web application instance has been stopped already

I suspect that this occurs after an attempt to undeploy your app. Do you ever kill off that thread that you've initialised during the init() process ? I would do this in the corresponding destroy() method.

How to Set AllowOverride all

SuSE Linux Enterprise Server

Make sure you are editing the right file https://www.suse.com/documentation/sles11/book_sle_admin/data/sec_apache2_configuration.html

httpd.conf

The main Apache server configuration file. Avoid changing this file. It primarily contains include statements and global settings. Overwrite global settings in the pertinent configuration files listed here. Change host-specific settings (such as document root) in your virtual host configuration.

In such case vhosts.d/*.conf must be edited

How can I remove all text after a character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

Timer for Python game

As a learning exercise for myself, I created a class to be able to create several stopwatch timer instances that you might find useful (I'm sure there are better/simpler versions around in the time modules or similar)

import time as tm
class Watch:
    count = 0
    description = "Stopwatch class object (default description)"
    author = "Author not yet set"
    name = "not defined"
    instances = []
    def __init__(self,name="not defined"):
        self.name = name
        self.elapsed = 0.
        self.mode = 'init'
        self.starttime = 0.
        self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
        Watch.count += 1

    def __call__(self):
        if self.mode == 'running':
            return tm.time() - self.starttime
        elif self.mode == 'stopped':
            return self.elapsed
        else:
            return 0.

    def display(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        print "Name:       ", self.name
        print "Address:    ", self
        print "Created:    ", self.created
        print "Start-time: ", self.starttime
        print "Mode:       ", self.mode
        print "Elapsed:    ", self.elapsed
        print "Description:", self.description
        print "Author:     ", self.author

    def start(self):
        if self.mode == 'running':
            self.starttime = tm.time()
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.starttime = tm.time()
            self.mode = 'running'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            self.mode = 'running'
            #self.elapsed = self.elapsed + tm.time() - self.starttime
            self.starttime = tm.time() - self.elapsed
        else:
            pass
        return

    def stop(self):
        if self.mode == 'running':
            self.mode = 'stopped'
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.mode = 'stopped'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def lap(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def reset(self):
        self.starttime=0.
        self.elapsed=0.
        self.mode='init'
        return self.elapsed

def WatchList():
    return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]

show distinct column values in pyspark dataframe: python

This should help to get distinct values of a column:

df.select('column1').distinct().collect()

Note that .collect() doesn't have any built-in limit on how many values can return so this might be slow -- use .show() instead or add .limit(20) before .collect() to manage this.

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Use tnsnames.ora in Oracle SQL Developer

  • In SQLDeveloper browse Tools --> Preferences, as shown in below image.

    SQLDeveloper access preferences

  • In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
  • Then click on Ok, as shown in below diagram.
    tnsnames.ora available at Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN

    SQLDeveloper update tnsnames directory

Now you can connect via the TNSnames options.