Programs & Examples On #Mmix

MMIX is the next generation version of Don Knuth's famous MIX assembly language. MMIX has a syntax modelled around modern RISC machines, but with none of the idiosyncrasies that are part of all real assembly languages. Thus MMIX is ideal for theoretical investigations around computer science algorithms, data structures, and their complexity. MMIX comes with an assembler and simulator. There are even FPGA implementations of the underlying hardware!

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

^[A-Za-z](\W|\w)*

(\W|\w) will ensure that every subsequent letter is word(\w) or non word(\W)

instead of (\W|\w)* you can also use .* where . means absolutely anything just like (\w|\W)

Convert row names into first column

Moved my comment into an answer per suggestion above:

You don't need extra packages, here's a one-liner:

d <- cbind(rownames(d), data.frame(d, row.names=NULL))

How to remove all ListBox items?

I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }

What is the default value for Guid?

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

How to get autocomplete in jupyter notebook without using tab?

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.

In Go's http package, how do I get the query string on a POST request?

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

Renaming the current file in Vim

You can also do it using netrw

The explore command opens up netrw in the directory of the open file

:E

Move the cursor over the file you want to rename:

R

Type in the new name, press enter, press y.

decompiling DEX into Java sourcecode

With Dedexer, you can disassemble the .dex file into dalvik bytecode (.ddx).

Decompiling towards Java isn't possible as far as I know.
You can read about dalvik bytecode here.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

One option if the number of keys is small is to use chained gets:

value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

But if you have keySet defined, this might be clearer:

value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]
        break

The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

How do I rotate the Android emulator display?

You can use Numpad-9 and Numpad-7 to rotate on Windows and Ubuntu.

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

server error:405 - HTTP verb used to access this page is not allowed

Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.

Blocks and yields in Ruby

There are two points I want to make about yield here. First, while a lot of answers here talk about different ways to pass a block to a method which uses yield, let's also talk about the control flow. This is especially relevant since you can yield MULTIPLE times to a block. Let's take a look at an example:

class Fruit
  attr_accessor :kinds

  def initialize 
    @kinds = %w(orange apple pear banana)
  end

  def each 
    puts 'inside each'
    3.times { yield (@kinds.tap {|kinds| puts "selecting from #{kinds}"} ).sample }
  end  
end

f = Fruit.new
f.each do |kind|
  puts 'inside block'
end    

=> inside each
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block

When the each method is invoked, it executes line by line. Now when we get to the 3.times block, this block will be invoked 3 times. Each time it invokes yield. That yield is linked to the block associated with the method that called the each method. It is important to notice that each time yield is invoked, it returns control back to the block of the each method in client code. Once the block is finished executing, it returns back to the 3.times block. And this happens 3 times. So that block in client code is invoked on 3 separate occasions since yield is explicitly called 3 separate times.

My second point is about enum_for and yield. enum_for instantiates the Enumerator class and this Enumerator object also responds to yield.

class Fruit
  def initialize
    @kinds = %w(orange apple)
  end

  def kinds
    yield @kinds.shift
    yield @kinds.shift
  end
end

f = Fruit.new
enum = f.to_enum(:kinds)
enum.next
 => "orange" 
enum.next
 => "apple" 

So notice every time we invoke kinds with the external iterator, it will invoke yield only once. The next time we call it, it will invoke the next yield and so on.

There's an interesting tidbit with regards to enum_for. The documentation online states the following:

enum_for(method = :each, *args) ? enum
Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }    
# => 120
# => 121
# => 122

If you do not specify a symbol as an argument to enum_for, ruby will hook the enumerator to the receiver's each method. Some classes do not have an each method, like the String class.

str = "I like fruit"
enum = str.to_enum
enum.next
=> NoMethodError: undefined method `each' for "I like fruit":String

Thus, in the case of some objects invoked with enum_for, you must be explicit as to what your enumerating method will be.

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

How to import a SQL Server .bak file into MySQL?

Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.

hope this helps

What's the difference between lists enclosed by square brackets and parentheses in Python?

Another way brackets and parentheses differ is that square brackets can describe a list comprehension, e.g. [x for x in y]

Whereas the corresponding parenthetic syntax specifies a tuple generator: (x for x in y)

You can get a tuple comprehension using: tuple(x for x in y)

See: Why is there no tuple comprehension in Python?

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

Viewing all `git diffs` with vimdiff

For people who want to use another diff tool not listed in git, say with nvim. here is what I ended up using:

git config --global alias.d difftool -x <tool name>

In my case, I set <tool name> to nvim -d and invoke the diff command with

git d <file>

How do I undo 'git add' before commit?

git remove or git rm can be used for this, with the --cached flag. Try:

git help rm

Git status shows files as changed even though contents are the same

I was able to fix the problems on Windows machine by changing core.autocrlf from false to core.autocrlf=input

git config core.autocrlf input

as it's suggested in https://stackoverflow.com/a/1112313/52277

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

"Please try running this command again as Root/Administrator" error when trying to install LESS

Honestly this is bad advice from npm. An installation can run arbitrary scripts and running it with sudo can be extremely dangerous! You could do sudo npm install -g less to install it globally, but instead I would recommend updating your npm settings:

#~/.npmrc
prefix=~/.npm_modules

Then you can update your path:

#~/.bashrc or ~/.zshrc, etc.
export PATH=$PATH:$HOME/.npm_modules/bin

Then you don't require root permissions to perform the installation and you can still use the binary.

This would only apply to your user, however. If you want the entire system to be able to use the module you would have to tell everyone to add your path. More complicated and robust solutions would include adding a folder with node modules / binaries that a group could install to and adding that to everyone's path.

How to implement onBackPressed() in Fragments?

If you're using androidx.appcompat:appcompat:1.1.0 or above then you can add an OnBackPressedCallback to your fragment as follows

requireActivity()
    .onBackPressedDispatcher
    .addCallback(this, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            Log.d(TAG, "Fragment back pressed invoked")
            // Do custom work here    

            // if you want onBackPressed() to be called as normal afterwards
            if (isEnabled) {
                isEnabled = false
                requireActivity().onBackPressed()
            }
        }
    }
)

See https://developer.android.com/guide/navigation/navigation-custom-back

How to hide a View programmatically?

Kotlin Solution

view.isVisible = true
view.isInvisible = true
view.isGone = true

// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone

Kotlin Extension Solution

If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:

// Example
view.hide()

fun View?.show() {
    if (this == null) return
    if (!isVisible) isVisible = true
}

fun View?.hide() {
    if (this == null) return
    if (!isInvisible) isInvisible = true
}

fun View?.gone() {
    if (this == null) return
    if (!isGone) isGone = true
}

To make conditional visibility simple, also add these:

fun View?.show(visible: Boolean) {
    if (visible) show() else gone()
}

fun View?.hide(hide: Boolean) {
    if (hide) hide() else show()
}

fun View?.gone(gone: Boolean = true) {
    if (gone) gone() else show()
}

Android : How to set onClick event for Button in List item of ListView

This has been discussed in many posts but still I could not figure out a solution with:

android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"

Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:

Adapter class - getview():

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            }
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(R.id.name);
            Button btn = (Button) view.findViewById(R.id.btn_check);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    context.doSelection(currentOrg);

                }
            });

       if(currentOrg.isSelected()){
            btn.setBackgroundResource(R.drawable.sub_search_tick);
        }else{
            btn.setBackgroundResource(R.drawable.sub_search_tick_box);
        }

    }

In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
            currentOrg.setSelected(true);
        } else {
            currentOrg.setSelected(false);
        }
        adapter.notifyDataSetChanged();

    }

How to access your website through LAN in ASP.NET

I'm not sure how stuck you are:

You must have a web server (Windows comes with one called IIS, but it may not be installed)

  1. Make sure you actually have IIS installed! Try typing http://localhost/ in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
  2. Set up IIS How to set up your first IIS Web site
  3. You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)

Installing your application

Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\. Read Installing ASP.NET Applications (IIS 6.0) for more information

Accessing the web site from another machine

In theory, once you have a web server running, and the application installed, you only need the IP address of your web server to access the application.

To find your IP address try: Start -> Run -> type cmd (hit ENTER) -> type ipconfig (hit ENTER)

Once

  • you have the IP address AND
  • IIS running AND
  • the application is installed

you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.

If you put your application in a directory called NewApp, you will need to type something like http://your_ip_address/NewApp/default.aspx

Turn off your firewall

If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.

Is there an ignore command for git like there is for svn?

for names not present in the working copy or repo:

echo /globpattern >> .gitignore

or for an existing file (sh type command line):

echo /$(ls -1 file) >> .gitignore   # I use tab completion to select the file to be ignored  
git rm -r --cached file             # if already checked in, deletes it on next commit

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

CRC32 C or C++ implementation

The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:

/* Copyright (C) 1986 Gary S. Brown.  You may use this program, or
   code or tables extracted from it, as desired without restriction.*/

(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)

In order to be able to compile the code, you'll need to add typedefs for BYTE as an unsigned 8-bit integer and DWORD as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.

The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:

#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

In the above answers, it is important to understand what is meant by "values are expanded at declaration/use time". Giving a value like *.c does not entail any expansion. It is only when this string is used by a command that it will maybe trigger some globbing. Similarly, a value like $(wildcard *.c) or $(shell ls *.c) does not entail any expansion and is completely evaluated at definition time even if we used := in the variable definition.

Try the following Makefile in directory where you have some C files:

VAR1 = *.c
VAR2 := *.c
VAR3 = $(wildcard *.c)
VAR4 := $(wildcard *.c)
VAR5 = $(shell ls *.c)
VAR6 := $(shell ls *.c)

all :
    touch foo.c
    @echo "now VAR1 = \"$(VAR1)\"" ; ls $(VAR1)
    @echo "now VAR2 = \"$(VAR2)\"" ; ls $(VAR2)
    @echo "now VAR3 = \"$(VAR3)\"" ; ls $(VAR3)
    @echo "now VAR4 = \"$(VAR4)\"" ; ls $(VAR4)
    @echo "now VAR5 = \"$(VAR5)\"" ; ls $(VAR5)
    @echo "now VAR6 = \"$(VAR6)\"" ; ls $(VAR6)
    rm -v foo.c

Running make will trigger a rule that creates an extra (empty) C file, called foo.c but none of the 6 variables has foo.c in its value.

How do I use Maven through a proxy?

Some times you need to add other <proxy></proxy> tags, and specify the https in the protocol tags: <protocol>https</protocol>

How do I change the IntelliJ IDEA default JDK?

I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:

JDK for importer.

IntelliJ 2020.3 Settings dialog

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

SyntaxError: unexpected EOF while parsing

There are some cases can lead to this issue, if it occered in the middle of the code it will be "IndentationError: expected an indented block" or "SyntaxError: invalid syntax", if it at the last line it may "SyntaxError: unexpected EOF while parsing":

Missing the body of "if","while"and"for" statement-->

root@nest:~/workplace# cat test.py
l = [1,2,3]
for i in l:
root@nest:~/workplace# python3 test.py
  File "test.py", line 3

               ^
SyntaxError: unexpected EOF while parsing

Unclosed parentheses (Especially in complex nested states)-->

root@nest:~/workplace# cat test.py
l = [1,2,3]
print( l
root@nest:~/workplace# python3 test.py
  File "test.py", line 3

            ^
SyntaxError: unexpected EOF while parsing

Find and replace in file and overwrite file doesn't work, it empties the file

And the ed answer:

printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html

To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.

How can I write a heredoc to a file in Bash script?

For future people who may have this issue the following format worked:

(cat <<- _EOF_
        LogFile /var/log/clamd.log
        LogTime yes
        DatabaseDirectory /var/lib/clamav
        LocalSocket /tmp/clamd.socket
        TCPAddr 127.0.0.1
        SelfCheck 1020
        ScanPDF yes
        _EOF_
) > /etc/clamd.conf

The server principal is not able to access the database under the current security context in SQL Server MS 2012

On SQL 2017 - Database A has synonyms to Database B. User can connect to database A and has exec rights to an sp (on A) that refers to the synonyms that point to B. User was set up with connect access B. Only when granting CONNECT to the public group to database B did the sp on A work. I don't recall this working this way on 2012 as granting connect to the user only seemed to work.

MySQL server has gone away - in exactly 60 seconds

By my experiences when it happens on light queries there is a way to solve the problem. It seems when you start or restart mysql after apache this problem starts to appear and the source of the problem is confused open sockets in the php process. To solve it:

  1. First restart mysql service

  2. Then restart apache service

Difference between \w and \b regular expression meta characters

@Mahender, you probably meant the difference between \W (instead of \w) and \b. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.

\W would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b can be thought of as (\W|^|$). [Edit: as @?mega mentions below, \b is a zero-length match so (\W|^|$) is not strictly correct, but hopefully helps explain the diff]

Quick example: For the string Hello World, .+\W would match Hello_ (with the space) but will not match World. .+\b would match both Hello and World.

Select NOT IN multiple columns

You should probably use NOT EXISTS for multiple columns.

Insert string at specified position

Strange answers here! You can insert strings into other strings easily with sprintf [link to documentation]. The function is extremely powerful and can handle multiple elements and other data types too.

$color = 'green';
sprintf('I like %s apples.', $color);

gives you the string

I like green apples.

How to read large text file on windows?

try this...

Large Text File Viewer

By the way, it is free :)

But, I think you should ask this on serverfault.com instead

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

Sometimes simplicity is the key to success. Search for while (i <= 10000) {} without increasing i in your code ;)

Passing data through intent using Serializable

Intent intent = new Intent(getApplicationContext(),SomeClass.class);
intent.putExtra("value",all_thumbs);
startActivity(intent);

In SomeClass.java

Bundle b = getIntent().getExtras();
if(b != null)
thumbs = (List<Thumbnail>) b.getSerializable("value");

How do I consume the JSON POST data in an Express application

I think you're conflating the use of the response object with that of the request.

The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

For earlier versions of Express (< 4)

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

Test along the lines of:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

Updated for Express 4+

Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

var express = require('express')
  , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Update for Express 4.16+

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Mocha / Chai expect.to.throw not catching thrown errors

One other possible implementation, more cumbersome than the .bind() solution, but one that helps to make the point that expect() requires a function that provides a this context to the covered function, you can use a call(), e.g.,

expect(function() {model.get.call(model, 'z');}).to.throw('...');

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

How to convert a String to CharSequence?

Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.

I need an unordered list without any bullets

You can hide them using ::marker pseudo-element.

  1. Transparent ::marker

ul li::marker {
  color: transparent;
}

_x000D_
_x000D_
ul li::marker {
  color: transparent;
}

ul {
  padding-inline-start: 10px; /* Just to reset the browser initial padding */
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> I want to remove them. </li>
  <li> Hey! ::marker to the rescue </li>
</ul>
_x000D_
_x000D_
_x000D_

  1. ::marker empty content

ul li::marker {
  content: "";
}

_x000D_
_x000D_
ul li::marker {
   content: "";
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> I want to remove them </li>
  <li> Hey! ::marker to the rescue </li>
</ul>
_x000D_
_x000D_
_x000D_

It is better when you need to remove bullets from a specific list item.

ul li:nth-child(n)::marker { /* Replace n with the list item's position*/
   content: "";
}

_x000D_
_x000D_
ul li:not(:nth-child(2))::marker {
   content: "";
}
_x000D_
<ul>
  <li> Bullets are bothersome </li>
  <li> But I can live with it using ::marker </li>
  <li> Not again though </li>
</ul>
_x000D_
_x000D_
_x000D_

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

Reset/remove CSS styles for element only

BETTER SOLUTION

Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

Thanks@Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ?So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.

Useful link:


Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css

Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/

https://github.com/monmomo04/resetCss.git

Fatal error: Call to undefined function imap_open() in PHP

If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:

;extension=php_imap.dll

to

extension=php_imap.dll

How can I align all elements to the left in JPanel?

My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.

//To align it to the left
p.add(b, BorderLayout.WEST);

//To align it to the right
p.add(b, BorderLayout.EAST);

//To align it at the top
p.add(b, BorderLayout.NORTH);

//To align it to the bottom
p.add(b, BorderLayout.SOUTH);

//To align it to the center
p.add(b, BorderLayout.CENTER);

Don't forget to import it as well by typing:

import java.awt.BorderLayout;

There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!

AES Encrypt and Decrypt

CryptoSwift Example

Updated SWIFT 4.*

func aesEncrypt() throws -> String {
    let encrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).encrypt([UInt8](self.data(using: .utf8)!))
    return Data(encrypted).base64EncodedString()
}

func aesDecrypt() throws -> String {
    guard let data = Data(base64Encoded: self) else { return "" }
    let decrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).decrypt([UInt8](data))
    return String(bytes: decrypted, encoding: .utf8) ?? self
}

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

VMware Workstation and Device/Credential Guard are not compatible

For those who might be encountering this issue with recent changes to your computer involving Hyper-V, you'll need to disable it while using VMWare or VirtualBox. They don't work together. Windows Sandbox and WSL 2 need the Hyper-V Hypervisor on, which currently breaks VMWare. Basically, you'll need to run the following commands to enable/disable Hyper-V services on next reboot.

To disable Hyper-V and get VMWare working, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype off

To re-enable Hyper-V and break VMWare for now, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype auto

You'll need to reboot after that. I've written a PowerShell script that will toggle this for you and confirm it with dialog boxes. It even self-elevates to Administrator using this technique so that you can just right click and run the script to quickly change your Hyper-V mode. It could easily be modified to reboot for you as well, but I personally didn't want that to happen. Save this as hypervisor.ps1 and make sure you've run Set-ExecutionPolicy RemoteSigned so that you can run PowerShell scripts.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "-windowstyle hidden & '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

Add-Type -AssemblyName System.Windows.Forms


$state = bcdedit /enum | Select-String -Pattern 'hypervisorlaunchtype\s*(\w+)\s*'


if ($state.matches.groups[1].ToString() -eq "Off"){

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Enable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype auto
        [System.Windows.Forms.MessageBox]::Show("Enabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

} else {

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Disable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype off
        [System.Windows.Forms.MessageBox]::Show("Disabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

}

Load dimension value from res/values/dimension.xml from source code

For those who just need to save some int value in the resources, you can do the following.

integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="default_value">100</integer>
</resources> 

Code

int defaultValue = getResources().getInteger(R.integer.default_value);

How to check if a subclass is an instance of a class at runtime?

if(view instanceof B)

This will return true if view is an instance of B or the subclass A (or any subclass of B for that matter).

PHP Convert String into Float/Double

Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.

From the documentation,

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value (PHP_INT_MAX) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval().

Thus, the solution is:

$string = "2968789218";
echo 'Original: ' . floatval($string) . PHP_EOL;
$string.= ".0";
$float = floatval($string);
echo 'Corrected: ' . $float . PHP_EOL;

which outputs:

Original: 2.00
Corrected: 2968789218

To check whether your PHP is 32-bit or 64-bit, you can:

echo PHP_INT_MAX;

If your PHP is 64-bit, it will print out 9223372036854775807, otherwise it will print out 2147483647.

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

asynchronous vs non-blocking

Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking. With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false). After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,

while (!isDataEnough()) {
    socketchannel.read(inputBuffer);
    // do something else and then read again
}

With the asynchronous api in java 7, these controls can be made in more versatile ways. One of the 2 ways is to use CompletionHandler. Notice that both read calls are non-blocking.

asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */, 
    new CompletionHandler<Integer, Object>() {
        public void completed(Integer result, Object attachment) {...}  
        public void failed(Throwable e, Object attachment) {...}
    }
}

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

How do I find the size of a struct?

The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.

If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.

The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Invariant Violation: Objects are not valid as a React child

Thanks to a comment by zerkms, I was able to notice my stupid mistake:

I had onItemClick(e, item) when I should have had onItemClick(item, e).

Can I configure a subdomain to point to a specific port on my server

With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host

How can I change cols of textarea in twitter-bootstrap?

This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row

 <div class="row" >
   <div class="span9">
     <%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>
   </div>
 </div>

Microsoft Visual C++ Compiler for Python 3.4

For the different python versions:

Visual C++ |CPython
--------------------
14.0       |3.5
10.0       |3.3, 3.4
9.0        |2.6, 2.7, 3.0, 3.1, 3.2

Source: Windows Compilers for py

Also refer: this answer

javax.faces.application.ViewExpiredException: View could not be restored

Introduction

The ViewExpiredException will be thrown whenever the javax.faces.STATE_SAVING_METHOD is set to server (default) and the enduser sends a HTTP POST request on a view via <h:form> with <h:commandLink>, <h:commandButton> or <f:ajax>, while the associated view state isn't available in the session anymore.

The view state is identified as value of a hidden input field javax.faces.ViewState of the <h:form>. With the state saving method set to server, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate() in server, or due a server specific bug with session cookies as known in WildFly), then the serialized view state is not available anymore in the session and the enduser will get this exception. To understand the working of the session, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.

There is also a limit on the amount of views JSF will store in the session. When the limit is hit, then the least recently used view will be expired. See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews.

With the state saving method set to client, the javax.faces.ViewState hidden input field contains instead the whole serialized view state, so the enduser won't get a ViewExpiredException when the session expires. It can however still happen on a cluster environment ("ERROR: MAC did not verify" is symptomatic) and/or when there's a implementation-specific timeout on the client side state configured and/or when server re-generates the AES key during restart, see also Getting ViewExpiredException in clustered environment while state saving method is set to client and user session is valid how to solve it.

Regardless of the solution, make sure you do not use enableRestoreView11Compatibility. it does not at all restore the original view state. It basically recreates the view and all associated view scoped beans from scratch and hereby thus losing all of original data (state). As the application will behave in a confusing way ("Hey, where are my input values..??"), this is very bad for user experience. Better use stateless views or <o:enableRestorableView> instead so you can manage it on a specific view only instead of on all views.

As to the why JSF needs to save view state, head to this answer: Why JSF saves the state of UI components on server?

Avoiding ViewExpiredException on page navigation

In order to avoid ViewExpiredException when e.g. navigating back after logout when the state saving is set to server, only redirecting the POST request after logout is not sufficient. You also need to instruct the browser to not cache the dynamic JSF pages, otherwise the browser may show them from the cache instead of requesting a fresh one from the server when you send a GET request on it (e.g. by back button).

The javax.faces.ViewState hidden field of the cached page may contain a view state ID value which is not valid anymore in the current session. If you're (ab)using POST (command links/buttons) instead of GET (regular links/buttons) for page-to-page navigation, and click such a command link/button on the cached page, then this will in turn fail with a ViewExpiredException.

To fire a redirect after logout in JSF 2.0, either add <redirect /> to the <navigation-case> in question (if any), or add ?faces-redirect=true to the outcome value.

<h:commandButton value="Logout" action="logout?faces-redirect=true" />

or

public String logout() {
    // ...
    return "index?faces-redirect=true";
}

To instruct the browser to not cache the dynamic JSF pages, create a Filter which is mapped on the servlet name of the FacesServlet and adds the needed response headers to disable the browser cache. E.g.

@WebFilter(servletNames={"Faces Servlet"}) // Must match <servlet-name> of your FacesServlet.
public class NoCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            res.setDateHeader("Expires", 0); // Proxies.
        }

        chain.doFilter(request, response);
    }

    // ...
}

Avoiding ViewExpiredException on page refresh

In order to avoid ViewExpiredException when refreshing the current page when the state saving is set to server, you not only need to make sure you are performing page-to-page navigation exclusively by GET (regular links/buttons), but you also need to make sure that you are exclusively using ajax to submit the forms. If you're submitting the form synchronously (non-ajax) anyway, then you'd best either make the view stateless (see later section), or to send a redirect after POST (see previous section).

Having a ViewExpiredException on page refresh is in default configuration a very rare case. It can only happen when the limit on the amount of views JSF will store in the session is hit. So, it will only happen when you've manually set that limit way too low, or that you're continuously creating new views in the "background" (e.g. by a badly implemented ajax poll in the same page or by a badly implemented 404 error page on broken images of the same page). See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews for detail on that limit. Another cause is having duplicate JSF libraries in runtime classpath conflicting each other. The correct procedure to install JSF is outlined in our JSF wiki page.

Handling ViewExpiredException

When you want to handle an unavoidable ViewExpiredException after a POST action on an arbitrary page which was already opened in some browser tab/window while you're logged out in another tab/window, then you'd like to specify an error-page for that in web.xml which goes to a "Your session is timed out" page. E.g.

<error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/WEB-INF/errorpages/expired.xhtml</location>
</error-page>

Use if necessary a meta refresh header in the error page in case you intend to actually redirect further to home or login page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Session expired</title>
        <meta http-equiv="refresh" content="0;url=#{request.contextPath}/login.xhtml" />
    </head>
    <body>
        <h1>Session expired</h1>
        <h3>You will be redirected to login page</h3>
        <p><a href="#{request.contextPath}/login.xhtml">Click here if redirect didn't work or when you're impatient</a>.</p>
    </body>
</html>

(the 0 in content represents the amount of seconds before redirect, 0 thus means "redirect immediately", you can use e.g. 3 to let the browser wait 3 seconds with the redirect)

Note that handling exceptions during ajax requests requires a special ExceptionHandler. See also Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request. You can find a live example at OmniFaces FullAjaxExceptionHandler showcase page (this also covers non-ajax requests).

Also note that your "general" error page should be mapped on <error-code> of 500 instead of an <exception-type> of e.g. java.lang.Exception or java.lang.Throwable, otherwise all exceptions wrapped in ServletException such as ViewExpiredException would still end up in the general error page. See also ViewExpiredException shown in java.lang.Throwable error-page in web.xml.

<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/errorpages/general.xhtml</location>
</error-page>

Stateless views

A completely different alternative is to run JSF views in stateless mode. This way nothing of JSF state will be saved and the views will never expire, but just be rebuilt from scratch on every request. You can turn on stateless views by setting the transient attribute of <f:view> to true:

<f:view transient="true">

</f:view>

This way the javax.faces.ViewState hidden field will get a fixed value of "stateless" in Mojarra (have not checked MyFaces at this point). Note that this feature was introduced in Mojarra 2.1.19 and 2.2.0 and is not available in older versions.

The consequence is that you cannot use view scoped beans anymore. They will now behave like request scoped beans. One of the disadvantages is that you have to track the state yourself by fiddling with hidden inputs and/or loose request parameters. Mainly those forms with input fields with rendered, readonly or disabled attributes which are controlled by ajax events will be affected.

Note that the <f:view> does not necessarily need to be unique throughout the view and/or reside in the master template only. It's also completely legit to redeclare and nest it in a template client. It basically "extends" the parent <f:view> then. E.g. in master template:

<f:view contentType="text/html">
    <ui:insert name="content" />
</f:view>

and in template client:

<ui:define name="content">
    <f:view transient="true">
        <h:form>...</h:form>
    </f:view>
</f:view>

You can even wrap the <f:view> in a <c:if> to make it conditional. Note that it would apply on the entire view, not only on the nested contents, such as the <h:form> in above example.

See also


Unrelated to the concrete problem, using HTTP POST for pure page-to-page navigation isn't very user/SEO friendly. In JSF 2.0 you should really prefer <h:link> or <h:button> over the <h:commandXxx> ones for plain vanilla page-to-page navigation.

So instead of e.g.

<h:form id="menu">
    <h:commandLink value="Foo" action="foo?faces-redirect=true" />
    <h:commandLink value="Bar" action="bar?faces-redirect=true" />
    <h:commandLink value="Baz" action="baz?faces-redirect=true" />
</h:form>

better do

<h:link value="Foo" outcome="foo" />
<h:link value="Bar" outcome="bar" />
<h:link value="Baz" outcome="baz" />

See also

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

Java null check why use == instead of .equals()

You could always do

if (str == null || str.equals(null))

This will first check the object reference and then check the object itself providing the reference isnt null.

How to get filename without extension from file path in Ruby

require 'pathname'

Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>

I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.

How to auto-size an iFrame?

I just happened to come by your question and i have a solution. But its in jquery. Its too simple.

$('iframe').contents().find('body').css({"min-height": "100", "overflow" : "hidden"});
setInterval( "$('iframe').height($('iframe').contents().find('body').height() + 20)", 1 );

There you go!

Cheers! :)

Edit: If you have a Rich Text Editor based on the iframe method and not the div method and want it to expand every new line then this code will do the needful.

How to succinctly write a formula with many variables from a data frame?

Yes of course, just add the response y as first column in the dataframe and call lm() on it:

d2<-data.frame(y,d)
> d2
  y x1 x2 x3
1 1  4  3  4
2 4 -1  9 -4
3 6  3  8 -2
> lm(d2)

Call:
lm(formula = d2)

Coefficients:
(Intercept)           x1           x2           x3  
    -5.6316       0.7895       1.1579           NA  

Also, my information about R points out that assignment with <- is recommended over =.

Check whether a string matches a regex in JS

Use regex.test() if all you want is a boolean result:

_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
_x000D_
_x000D_
_x000D_

...and you could remove the () from your regexp since you've no need for a capture.

Get a resource using getResource()

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");

How to set radio button checked as default in radiogroup?

Add android:checked = "true" in your activity.xml

Presenting a UIAlertController properly on an iPad using iOS 8

Swift 4 and above

I have created an extension

extension UIViewController {
  public func addActionSheetForiPad(actionSheet: UIAlertController) {
    if let popoverPresentationController = actionSheet.popoverPresentationController {
      popoverPresentationController.sourceView = self.view
      popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
      popoverPresentationController.permittedArrowDirections = []
    }
  }
}

How to use:

let actionSheetVC = UIAlertController(title: "Title", message: nil, preferredStyle: .actionSheet)
addActionSheetForIpad(actionSheet: actionSheetVC)
present(actionSheetVC, animated: true, completion: nil)

How to compare each item in a list with the rest, only once?

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
    for that in mylist[index+1:]:
        compare(this, that)

Regex pattern inside SQL Replace function?

I think a simpler and faster approach is iterate by each character of the alphabet:

DECLARE @i int
SET @i = 0

WHILE(@i < 256)
BEGIN  

    IF char(@i) NOT IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')      

      UPDATE Table SET Column = replace(Column, char(@i), '')

    SET @i = @i + 1

END

Check if an apt-get package is installed and then install it if it's not on Linux

This command is the most memorable:

dpkg --get-selections <package-name>

If it's installed it prints:

<package-name> install

Otherwise it prints

No packages found matching <package-name>.

This was tested on Ubuntu 12.04.1 (Precise Pangolin).

Best HTML5 markup for sidebar

Look at the following example, from the HTML5 specification about aside.

It makes clear that what currently is recommended (October 2012) it is to group widgets inside aside elements. Then, each widget is whatever best represents it, a nav, a serie of blockquotes, etc

The following extract shows how aside can be used for blogrolls and other side content on a blog:

<body>
 <header>
  <h1>My wonderful blog</h1>
  <p>My tagline</p>
 </header>
 <aside>
  <!-- this aside contains two sections that are tangentially related
  to the page, namely, links to other blogs, and links to blog posts
  from this blog -->
  <nav>
   <h1>My blogroll</h1>
   <ul>
    <li><a href="http://blog.example.com/">Example Blog</a>
   </ul>
  </nav>
  <nav>
   <h1>Archives</h1>
   <ol reversed>
    <li><a href="/last-post">My last post</a>
    <li><a href="/first-post">My first post</a>
   </ol>
  </nav>
 </aside>
 <aside>
  <!-- this aside is tangentially related to the page also, it
  contains twitter messages from the blog author -->
  <h1>Twitter Feed</h1>
  <blockquote cite="http://twitter.example.net/t31351234">
   I'm on vacation, writing my blog.
  </blockquote>
  <blockquote cite="http://twitter.example.net/t31219752">
   I'm going to go on vacation soon.
  </blockquote>
 </aside>
 <article>
  <!-- this is a blog post -->
  <h1>My last post</h1>
  <p>This is my last post.</p>
  <footer>
   <p><a href="/last-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <article>
  <!-- this is also a blog post -->
  <h1>My first post</h1>
  <p>This is my first post.</p>
  <aside>
   <!-- this aside is about the blog post, since it's inside the
   <article> element; it would be wrong, for instance, to put the
   blogroll here, since the blogroll isn't really related to this post
   specifically, only to the page as a whole -->
   <h1>Posting</h1>
   <p>While I'm thinking about it, I wanted to say something about
   posting. Posting is fun!</p>
  </aside>
  <footer>
   <p><a href="/first-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <footer>
  <nav>
   <a href="/archives">Archives</a> —
   <a href="/about">About me</a> —
   <a href="/copyright">Copyright</a>
  </nav>
 </footer>
</body>

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

How to git reset --hard a subdirectory?

Try changing

git checkout -- a

to

git checkout -- `git ls-files -m -- a`

Since version 1.7.0, Git's ls-files honors the skip-worktree flag.

Running your test script (with some minor tweaks changing git commit... to git commit -q and git status to git status --short) outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba

Running your test script with the proposed checkout change outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/b/ab
b/a/ba

Where to put a textfile I want to use in eclipse?

MJB

Please try this

  1. In eclipse "Right click" on the text file u wanna use, see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")

  2. put this complete path and try.

  3. if it works then class-path issue else GOK :)

Using Helvetica Neue in a Website

I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:

http://css-tricks.com/snippets/css/better-helvetica/

He basically recommends the following declaration for covering all the bases:

body {
    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
    font-weight: 300;
}

Eclipse Problems View not showing Errors anymore

Check your filters, sometimes problem view could be scoped to a working set that you are not currently working in. Also, you can check other configurations for the problem view.

enter image description here

Android "elevation" not showing a shadow

Also check if You don't change alpha on that view. I am investigating issue when i change alpha on some views, with elevation. They simply loose elevation when alpha is changed and changed back to 1f.

Get table names using SELECT statement in MySQL

To insert, update and delete do the following:

$teste = array('LOW_PRIORITY', 'DELAYED', 'HIGH_PRIORITY', 'IGNORE', 'INTO', 'INSERT', 'UPDATE', 'DELETE', 'QUICK', 'FROM');
$teste1 = array("\t", "\n", "\r", "\0", "\x0B");
$strsql = trim(str_ireplace($teste1, ' ', str_ireplace($teste, '', $strsql)));
$nomeTabela = substr($strsql, 0, strpos($strsql, ' '));

print($nomeTabela);
exit;

What is sys.maxint in Python 3?

Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

This error may be about password characters. If your password contains special characters and also you add your password into Transport class methods;

For Example

Transport transport = session.getTransport("smtp");
transport.connect("user","passw@rd");

or

Transport.send(msg, "user", "passw%rd");

you may get that error. Because Transport class' methods may not handle special characters. If you add your username and password into your message using javax.mail.PasswordAuthentication class, i hope you will escape that error;

For Example

...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication("user", "pas$w@r|d");
  }
});

Message message = new MimeMessage(session);
...
Transport.send(message);

How to copy part of an array to another array in C#?

See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().

A purportedly faster extension method is described here.

Get the client's IP address in socket.io

If you use an other server as reverse proxy all of the mentioned fields will contain localhost. The easiest workaround is to add headers for ip/port in the proxy server.

Example for nginx: add this after your proxy_pass:

proxy_set_header  X-Real-IP $remote_addr;
proxy_set_header  X-Real-Port $remote_port;

This will make the headers available in the socket.io node server:

var ip = socket.handshake.headers["x-real-ip"];
var port = socket.handshake.headers["x-real-port"];

Note that the header is internally converted to lower case.

If you are connecting the node server directly to the client,

var ip = socket.conn.remoteAddress;

works with socket.io version 1.4.6 for me.

How to run a jar file in a linux commandline

For example to execute from terminal (Ubuntu Linux) or even (Windows console) a java file called filex.jar use this command:

java -jar filex.jar

The file will execute in terminal.

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,workflow
        ,date
        ,other_columns
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1

How to get Chrome to allow mixed content?

On OSX the following works from the command line:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content

Polynomial time and exponential time

o(n sequre) is polynimal time complexity while o(2^n) is exponential time complexity if p=np when best case , in the worst case p=np not equal becasue when input size n grow so long or input sizer increase so longer its going to worst case and handling so complexity growth rate increase and depend on n size of input when input is small it is polynimal when input size large and large so p=np not equal it means growth rate depend on size of input "N". optimization, sat, clique, and independ set also met in exponential to polynimal.

C++ IDE for Linux?

make + vim + gdb = one great IDE

How to reverse apply a stash?

How to reverse apply a stash?

Apart from what others have mentioned, easiest way is first do

git reset HEAD

and then checkout all local changes

git checkout . 

applying css to specific li class

I only see one color being specified (albeit you specify it in two different places.) Either you've omitted some of your style rules, or you simply didn't specify another color.

Is there an eval() function in Java?

There are very few real use cases in which being able to evaluate a String as a fragment of Java code is necessary or desirable. That is, asking how to do this is really an XY problem: you actually have a different problem, which can be solved a different way.

First ask yourself, where did this String that you wish to evaluate come from? Did another part of your program generate it, or was it input provided by the user?

  • Another part of my program generated it: so, you want one part of your program to decide the kind of operation to perform, but not perform the operation, and a second part that performs the chosen operation. Instead of generating and then evaluating a String, use the Strategy, Command or Builder design pattern, as appropriate for your particular case.

  • It is user input: the user could input anything, including commands that, when executed, could cause your program to misbehave, crash, expose information that should be secret, damage persistent information (such as the content of a database), and other such nastiness. The only way to prevent that would be to parse the String yourself, check it was not malicious, and then evaluate it. But parsing it yourself is much of the work that the requested evalfunction would do, so you have saved yourself nothing. Worse still, checking that arbitrary Java was not malicious is impossible, because checking that is the halting problem.

  • It is user input, but the syntax and semantics of permitted text to evaluate is greatly restricted: No general purpose facility can easily implement a general purpose parser and evaluator for whatever restricted syntax and semantics you have chosen. What you need to do is implement a parser and evaluator for your chosen syntax and semantics. If the task is simple, you could write a simple recursive-descent or finite-state-machine parser by hand. If the task is difficult, you could use a compiler-compiler (such as ANTLR) to do some of the work for you.

  • I just want to implement a desktop calculator!: A homework assignment, eh? If you could implement the evaluation of the input expression using a provided eval function, it would not be much of a homework assignment, would it? Your program would be three lines long. Your instructor probably expects you to write the code for a simple arithmetic parser/evaluator. There is well known algorithm, shunting-yard, which you might find useful.

Tab key == 4 spaces and auto-indent after curly braces in Vim

Related, if you open a file that uses both tabs and spaces, assuming you've got

set expandtab ts=4 sw=4 ai

You can replace all the tabs with spaces in the entire file with

:%retab

Get multiple elements by Id

Use jquery multiple selector.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>

Link : http://api.jquery.com/multiple-selector/

selector should like this : $("#id1,#id2,#id3")

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

How do I read any request header in PHP

You should find all HTTP headers in the $_SERVER global variable prefixed with HTTP_ uppercased and with dashes (-) replaced by underscores (_).

For instance your X-Requested-With can be found in:

$_SERVER['HTTP_X_REQUESTED_WITH']

It might be convenient to create an associative array from the $_SERVER variable. This can be done in several styles, but here's a function that outputs camelcased keys:

$headers = array();
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
    }
}

Now just use $headers['XRequestedWith'] to retrieve the desired header.

PHP manual on $_SERVER: http://php.net/manual/en/reserved.variables.server.php

How to add column if not exists on PostgreSQL?

CREATE OR REPLACE function f_add_col(_tbl regclass, _col  text, _type regtype)
  RETURNS bool AS
$func$
BEGIN
   IF EXISTS (SELECT 1 FROM pg_attribute
              WHERE  attrelid = _tbl
              AND    attname = _col
              AND    NOT attisdropped) THEN
      RETURN FALSE;
   ELSE
      EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
      RETURN TRUE;
   END IF;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT f_add_col('public.kat', 'pfad1', 'int');

Returns TRUE on success, else FALSE (column already exists).
Raises an exception for invalid table or type name.

Why another version?

  • This could be done with a DO statement, but DO statements cannot return anything. And if it's for repeated use, I would create a function.

  • I use the object identifier types regclass and regtype for _tbl and _type which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col has still to be sanitized for EXECUTE with quote_ident(). More explanation in this related answer:

  • format() requires Postgres 9.1+. For older versions concatenate manually:

    EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
    
  • You can schema-qualify your table name, but you don't have to.
    You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).

  • I query pg_catalog instead of the information_schema. Detailed explanation:

  • Blocks containing an EXCEPTION clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:

Tip: A block containing an EXCEPTION clause is significantly more expensive to enter and exit than a block without one. Therefore, don't use EXCEPTION without need.

Set color of TextView span in Android

I always find visual examples helpful when trying to understand a new concept.

Background Color

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Foreground Color

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Combination

enter image description here

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Further Study

Trim spaces from start and end of string

I know this is an old post, but just thought I'd share our solution. In the quest for shortest code (doesn't everyone just love terse regex), one could instead use:

title = title.replace(/(^\s+|\s+$)/g, '');

BTW: I ran this same test through the link shared above blog.stevenlevithan.com -- Faster JavaScript Trim and this pattern beat all the other HANDS down!

Using IE8, added test as test13. The results were:

Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)

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

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

How to generate java classes from WSDL file

You can use the eclipse plugin as suggested by Oscar earlier. Or if you are a command line person, you can use Apache Axis WSDL2Java tool from command prompt. You can find more details here http://axis.apache.org/axis/java/reference.html#WSDL2JavaReference

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I like to keep is simple when possible. I needed to group by International, filter on all the columns, display the count for each group and hide the group if no items existed.

Plus I did not want to add a custom filter just for something simple like this.

        <tbody>
            <tr ng-show="fusa.length > 0"><td colspan="8"><h3>USA ({{fusa.length}})</h3></td></tr>
            <tr ng-repeat="t in fusa = (usa = (vm.assignmentLookups | filter: {isInternational: false}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>
        <tbody>
            <tr ng-show="fint.length > 0"><td colspan="8"><h3>International ({{fint.length}})</h3></td></tr>
            <tr ng-repeat="t in fint = (int = (vm.assignmentLookups | filter: {isInternational: true}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>

Is there a simple way to convert C++ enum to string?

I want to post this in case someone finds it useful.

In my case, I simply need to generate ToString() and FromString() functions for a single C++11 enum from a single .hpp file.

I wrote a python script that parses the header file containing the enum items and generates the functions in a new .cpp file.

You can add this script in CMakeLists.txt with execute_process, or as a pre-build event in Visual Studio. The .cpp file will be automatically generated, without the need to manually update it each time a new enum item is added.

generate_enum_strings.py

# This script is used to generate strings from C++ enums

import re
import sys
import os

fileName = sys.argv[1]
enumName = os.path.basename(os.path.splitext(fileName)[0])

with open(fileName, 'r') as f:
    content = f.read().replace('\n', '')

searchResult = re.search('enum(.*)\{(.*?)\};', content)
tokens = searchResult.group(2)
tokens = tokens.split(',')
tokens = map(str.strip, tokens)
tokens = map(lambda token: re.search('([a-zA-Z0-9_]*)', token).group(1), tokens)

textOut = ''
textOut += '\n#include "' + enumName + '.hpp"\n\n'
textOut += 'namespace myns\n'
textOut += '{\n'
textOut += '    std::string ToString(ErrorCode errorCode)\n'
textOut += '    {\n'
textOut += '        switch (errorCode)\n'
textOut += '        {\n'

for token in tokens:
    textOut += '        case ' + enumName + '::' + token + ':\n'
    textOut += '            return "' + token + '";\n'

textOut += '        default:\n'
textOut += '            return "Last";\n'
textOut += '        }\n'
textOut += '    }\n'
textOut += '\n'
textOut += '    ' + enumName + ' FromString(const std::string &errorCode)\n'
textOut += '    {\n'
textOut += '        if ("' + tokens[0] + '" == errorCode)\n'
textOut += '        {\n'
textOut += '            return ' + enumName + '::' + tokens[0] + ';\n'
textOut += '        }\n'

for token in tokens[1:]:
    textOut += '        else if("' + token + '" == errorCode)\n'
    textOut += '        {\n'
    textOut += '            return ' + enumName + '::' + token + ';\n'
    textOut += '        }\n'

textOut += '\n'
textOut += '        return ' + enumName + '::Last;\n'
textOut += '    }\n'
textOut += '}\n'

fileOut = open(enumName + '.cpp', 'w')
fileOut.write(textOut)

Example:

ErrorCode.hpp

#pragma once

#include <string>
#include <cstdint>

namespace myns
{
    enum class ErrorCode : uint32_t
    {
        OK = 0,
        OutOfSpace,
        ConnectionFailure,
        InvalidJson,
        DatabaseFailure,
        HttpError,
        FileSystemError,
        FailedToEncrypt,
        FailedToDecrypt,
        EndOfFile,
        FailedToOpenFileForRead,
        FailedToOpenFileForWrite,
        FailedToLaunchProcess,

        Last
    };

    std::string ToString(ErrorCode errorCode);
    ErrorCode FromString(const std::string &errorCode);
}

Run python generate_enum_strings.py ErrorCode.hpp

Result:

ErrorCode.cpp

#include "ErrorCode.hpp"

namespace myns
{
    std::string ToString(ErrorCode errorCode)
    {
        switch (errorCode)
        {
        case ErrorCode::OK:
            return "OK";
        case ErrorCode::OutOfSpace:
            return "OutOfSpace";
        case ErrorCode::ConnectionFailure:
            return "ConnectionFailure";
        case ErrorCode::InvalidJson:
            return "InvalidJson";
        case ErrorCode::DatabaseFailure:
            return "DatabaseFailure";
        case ErrorCode::HttpError:
            return "HttpError";
        case ErrorCode::FileSystemError:
            return "FileSystemError";
        case ErrorCode::FailedToEncrypt:
            return "FailedToEncrypt";
        case ErrorCode::FailedToDecrypt:
            return "FailedToDecrypt";
        case ErrorCode::EndOfFile:
            return "EndOfFile";
        case ErrorCode::FailedToOpenFileForRead:
            return "FailedToOpenFileForRead";
        case ErrorCode::FailedToOpenFileForWrite:
            return "FailedToOpenFileForWrite";
        case ErrorCode::FailedToLaunchProcess:
            return "FailedToLaunchProcess";
        case ErrorCode::Last:
            return "Last";
        default:
            return "Last";
        }
    }

    ErrorCode FromString(const std::string &errorCode)
    {
        if ("OK" == errorCode)
        {
            return ErrorCode::OK;
        }
        else if("OutOfSpace" == errorCode)
        {
            return ErrorCode::OutOfSpace;
        }
        else if("ConnectionFailure" == errorCode)
        {
            return ErrorCode::ConnectionFailure;
        }
        else if("InvalidJson" == errorCode)
        {
            return ErrorCode::InvalidJson;
        }
        else if("DatabaseFailure" == errorCode)
        {
            return ErrorCode::DatabaseFailure;
        }
        else if("HttpError" == errorCode)
        {
            return ErrorCode::HttpError;
        }
        else if("FileSystemError" == errorCode)
        {
            return ErrorCode::FileSystemError;
        }
        else if("FailedToEncrypt" == errorCode)
        {
            return ErrorCode::FailedToEncrypt;
        }
        else if("FailedToDecrypt" == errorCode)
        {
            return ErrorCode::FailedToDecrypt;
        }
        else if("EndOfFile" == errorCode)
        {
            return ErrorCode::EndOfFile;
        }
        else if("FailedToOpenFileForRead" == errorCode)
        {
            return ErrorCode::FailedToOpenFileForRead;
        }
        else if("FailedToOpenFileForWrite" == errorCode)
        {
            return ErrorCode::FailedToOpenFileForWrite;
        }
        else if("FailedToLaunchProcess" == errorCode)
        {
            return ErrorCode::FailedToLaunchProcess;
        }
        else if("Last" == errorCode)
        {
            return ErrorCode::Last;
        }

        return ErrorCode::Last;
    }
}

Maven: How to include jars, which are not available in reps into a J2EE project?

@Ric Jafe's solution is what worked for me.

This is exactly what I was looking for. A way to push it through for research test code. Nothing fancy. Yeah I know that that's what they all say :) The various maven plugin solutions seem to be overkill for my purposes. I have some jars that were given to me as 3rd party libs with a pom file. I want it to compile/run quickly. This solution which I trivially adapted to python worked wonders for me. Cut and pasted into my pom. Python/Perl code for this task is in this Q&A: Can I add jars to maven 2 build classpath without installing them?

def AddJars(jarList):
  s1 = ''
  for elem in jarList:
   s1+= """
     <dependency>
        <groupId>local.dummy</groupId>
        <artifactId>%s</artifactId>
        <version>0.0.1</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/manual_jars/%s</systemPath>
     </dependency>\n"""%(elem, elem)
  return s1

Make an HTTP request with android

Note: The Apache HTTP Client bundled with Android is now deprecated in favor of HttpURLConnection. Please see the Android Developers Blog for more details.

Add <uses-permission android:name="android.permission.INTERNET" /> to your manifest.

You would then retrieve a web page like so:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
}
finally {
     urlConnection.disconnect();
}

I also suggest running it on a separate thread:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
    String responseString = null;
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
            // Do normal input or output stream reading
        }
        else {
            response = "FAILED"; // See documentation for more info on response handling
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Do anything with response..
}
}

See the documentation for more information on response handling and POST requests.

How do I compute derivative using Numpy?

I'll throw another method on the pile...

scipy.interpolate's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1), the derivative of the spline (using the derivative() method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.

from scipy.interpolate import InterpolatedUnivariateSpline

# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)

# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()

# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)

How do I seed a random class to avoid getting duplicate random values

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Disable Buttons in jQuery Mobile

You are getting that error probably because the element is not within the DOM yet. $(document).ready(); will not work. Try adding your code to a pageinit event handler.

Here is a working example:

<!DOCTYPE html> 
<html> 
<head>
    <title>Button Disable</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head> 
<body>
    <div id="MyPageId" data-role="page">
        <div data-role="header">
            <h1>Button Disable</h1>
        </div>
        <div data-role="content">
            <button id="button1" type="button" onclick="javascript:alert('#button1 clicked');">Button 1</button>
            <button id="button2" type="button" onclick="javascript:alert('#button2 clicked');">Button 2</button>
        </div>
        <div data-role="footer">
            <p>footer</p>
        </div>
    </div>
    <script type="text/javascript">//<![CDATA[
        $('#MyPageId').bind("pageinit", function (event, data) {
            $("#button1").button("disable");
        });
    //]]></script>
</body>
</html>

Hope that helps someone

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

Get the last insert id with doctrine 2?

More simple: SELECT max(id) FROM client

How to open a different activity on recyclerView item onclick

Simply you can do it easy... You just need to get the context of your activity, here, from your View.

//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion

Remember that you need to modify AndroidManifest.xml and place the activity...

<activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>

javascript windows alert with redirect function

Alert will block the program flow so you can just write the following.

echo ("<script LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated');
    window.location.href='http://someplace.com';
    </script>");

How to create a cron job using Bash automatically without the interactive editor?

script function to add cronjobs. check duplicate entries,useable expressions * > "

cronjob_creator () {         
# usage: cronjob_creator '<interval>' '<command>'

  if [[ -z $1 ]] ;then
    printf " no interval specified\n"
elif [[ -z $2 ]] ;then
    printf " no command specified\n"
else
    CRONIN="/tmp/cti_tmp"
    crontab -l | grep -vw "$1 $2" > "$CRONIN"
    echo "$1 $2" >> $CRONIN
    crontab "$CRONIN"
    rm $CRONIN
fi
}

tested :

$ ./cronjob_creator.sh '*/10 * * * *' 'echo "this is a test" > export_file'
$ crontab  -l
$ */10 * * * * echo "this is a test" > export_file

source : my brain ;)

Tomcat 7 "SEVERE: A child container failed during start"

for me one case was I just missed to maven update project which caused the same issue

maven update project and try if you see any errors in POM.xml

How to reset radiobuttons in jQuery so that none is checked

<div id="radio">
<input type="radio" id="radio1" name="radio"/><label for="radio1">Bar Chart</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Pie Chart</label>
<input type="radio" id="radio3" name="radio"/><label for="radio3">Datapoint Chart</label>
</div>

$('#radio input').removeAttr('checked');
// Refresh the jQuery UI buttonset.                  
$( "#radio" ).buttonset('refresh');

Simple check for SELECT query empty result

I agree with Ed B. You should use EXISTS method but a more efficient way to do this is:

IF EXISTS(SELECT 1 FROM service s WHERE s.service_id = ?)
BEGIN
   --DO STUFF HERE

END

HTH

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

What is the difference between hg forget and hg remove?

A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.

Plot a bar using matplotlib using a dictionary

Why not just:

names, counts = zip(*D.items())
plt.bar(names, counts)

enter image description here

calculate the mean for each column of a matrix in R

You can try this:

mean(as.matrix(cluster1))

What does functools.wraps do?

this is the source code about wraps:

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')

WRAPPER_UPDATES = ('__dict__',)

def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):

    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    """Decorator factory to apply update_wrapper() to a wrapper function

   Returns a decorator that invokes update_wrapper() with the decorated
   function as the wrapper argument and the arguments to wraps() as the
   remaining arguments. Default arguments are as for update_wrapper().
   This is a convenience function to simplify applying partial() to
   update_wrapper().
    """
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

Convert a list to a string in C#

The direct answer to your question is String.Join as others have mentioned.

However, if you need some manipulations, you can use Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();

Find length of 2D array Python

In addition, correct way to count total item number would be:

sum(len(x) for x in input)

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

Disable/turn off inherited CSS3 transitions

You could also disinherit all transitions inside a containing element:

CSS:

.noTrans *{
-moz-transition: none;
-webkit-transition: none;
-o-transition: color 0 ease-in;
transition: none;
}

HTML:

<a href="#">Content</a>
<a href="#">Content</a>
<div class="noTrans">
<a href="#">Content</a>
</div>
<a href="#">Content</a>

How can I get the timezone name in JavaScript?

In javascript , the Date.getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

Moment'timezone will be a useful tool. http://momentjs.com/timezone/

Convert Dates Between Timezones

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

How to know/change current directory in Python shell?

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

How to check syslog in Bash on Linux?

By default it's logged into system log at /var/log/syslog, so it can be read by:

tail -f /var/log/syslog

If the file doesn't exist, check /etc/syslog.conf to see configuration file for syslogd. Note that the configuration file could be different, so check the running process if it's using different file:

# ps wuax | grep syslog
root      /sbin/syslogd -f /etc/syslog-knoppix.conf

Note: In some distributions (such as Knoppix) all logged messages could be sent into different terminal (e.g. /dev/tty12), so to access e.g. tty12 try pressing Control+Alt+F12.

You can also use lsof tool to find out which log file the syslogd process is using, e.g.

sudo lsof -p $(pgrep syslog) | grep log$ 

To send the test message to syslogd in shell, you may try:

echo test | logger

For troubleshooting use a trace tool (strace on Linux, dtruss on Unix), e.g.:

sudo strace -fp $(cat /var/run/syslogd.pid)

Property getters and setters

You are recursively defining x with x. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.

You must say I am twice John's age or any other variable but yourself.

computed variables are always dependent on another variable.


The rule of the thumb is never access the property itself from within the getter ie get. Because that would trigger another get which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!

struct Person{
    var name: String{
        get{
            print(name) // DON'T do this!!!!
            return "as"
        }
        set{
        }
    }
}

let p1 = Person()

As that would give the following warning:

Attempting to access 'name' from within it's own getter.

The error looks vague like this:

enter image description here

As an alternative you might want to use didSet. With didSet you'll get a hold to the value that is was set before and just got set to. For more see this answer.

PHP - Debugging Curl

To just get the info of a CURL request do this:

$response = curl_exec($ch);

$info = curl_getinfo($ch);
var_dump($info);

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

Getting Data from Android Play Store

Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.

As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:

  • Make sure the URL you are trying to parse is not blocked in robots.txt - e.g. https://play.google.com/robots.txt
  • Make sure that you are not doing it too often, Google will throttle and potentially blacklist you if you are doing it too much.
  • Send a correct User-Agent header to actually show you are a bot
  • The page of an app is big - make sure you accept gzip and request the mobile version
  • GPlay website is not an API, it doesn't care that you parse it so it will change over time. Make sure you handle changes - e.g. by having test to make sure you get what you expected.

So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:

      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet(crawlUrl);
      HttpResponse rsp = httpClient.execute(request);

      int statusCode = rsp.getStatusLine().getStatusCode();

      if (statusCode == 200) {
           String content = EntityUtils.toString(rsp.getEntity());    
           Document doc = Jsoup.parse(content);
           //parse content, whatever you need
           Element price = doc.select("[itemprop=price]").first();
      }      

For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:

  • Search is forbidden in robots.
  • Keeping app metadata up-to-date is hard to do. There are more than 2.2m apps, if you want to refresh their metadata daily there are 2.2 requests/day, which will 1) get blocked immediately, 2) costs a lot of money - pessimistic 220gb data transfer per day if one app is 100k
  • How do you discover new apps
  • How do you get pricing in each country, translations of each language

The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.

[2]:

How to convert List to Json in Java

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

Is either GET or POST more secure than the other?

As far as security, they are inherently the same. While it is true that POST doesn't expose information via the URL, it exposes just as much information as a GET in the actual network communication between the client and server. If you need to pass information that is sensitive, your first line of defense would be to pass it using Secure HTTP.

GET or query string posts are really good for information required for either bookmarking a particular item, or for assisting in search engine optimization and indexing items.

POST is good for standard forms used to submit one time data. I wouldn't use GET for posting actual forms, unless maybe in a search form where you want to allow the user to save the query in a bookmark, or something along those lines.

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

How to get all table names from a database?

@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{ 

    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
    DatabaseMetaData md = con.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
    List<String> tables = new ArrayList<String>();
    String db = "";
    while (rs.next()) {
        tables.add(rs.getString(3));
        db = rs.getString(1);
    }
    List<String> database = new ArrayList<String>();
    database.add(db);
    databaseTables.put("database", database);
    Collections.reverse(tables);
    databaseTables.put("tables", tables);
    return new ObjectMapper().writeValueAsString(databaseTables);
}

@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{ 
    System.out.println("...tablename......"+tablename);
    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();       
     Statement st = con.createStatement();
     String sql = "select * from "+tablename;
     ResultSet rs = st.executeQuery(sql);
     ResultSetMetaData metaData = rs.getMetaData();
     int rowCount = metaData.getColumnCount();    
     List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
     HashMap<String,String> columnDetails = new HashMap<String,String>();
     for (int i = 0; i < rowCount; i++) {
         columnDetails = new HashMap<String,String>();
         Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
         method.setAccessible(true);
         com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
         columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
         columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
         columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
         columnDetails.put("columnColl", field.getCollation());
         columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
         if (field.isPrimaryKey()) {
             columnDetails.put("columnKEY", "PRI");
         } else if(field.isMultipleKey()) {
             columnDetails.put("columnKEY", "MUL");
         } else if(field.isUniqueKey()) {
             columnDetails.put("columnKEY", "UNI");
         } else {
             columnDetails.put("columnKEY", "");
         }
         columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
         databaseColumns.add(columnDetails);
     }
    HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
    Collections.reverse(databaseColumns);
    tableColumns.put("columns", databaseColumns);
    return new ObjectMapper().writeValueAsString(tableColumns);
}

Package opencv was not found in the pkg-config search path

it seems that the ubuntu community has completed the documentation on installing openCV,

so all you have to do now is to download the installation script from here and execute it.

don't forget to make it executable:

chmod +x opencv_latest.sh

then

./opencv_latest.sh

Center content vertically on Vuetify

<v-container> has to be right after <template>, if there is a <div> in between, the vertical align will just not work.

<template>
  <v-container fill-height>
      <v-row class="justify-center align-center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
      </v-row>
  </v-container>
</template>

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

What is the SQL command to return the field names of a table?

This is also MySQL Specific:

show fields from [tablename];

this doesnt just show the table names but it also pulls out all the info about the fields.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I encountered a similar error with while attempting to play an audio file. At first, it was working, then it stopped working when I started using ChangeDetector's markForCheck method in the same function to trigger a re-render when a promise resolves (I had an issue with view rendering).

When I changed the markForCheck to detectChanges it started working again. I really can't explain what happened, I just thought of dropping this here, perhaps it would help someone.

How do I create delegates in Objective-C?

When using the formal protocol method for creating delegate support, I've found that you can ensure proper type checking (albeit, runtime, not compile time) by adding something like:

if (![delegate conformsToProtocol:@protocol(MyDelegate)]) {
    [NSException raise:@"MyDelegate Exception"
                format:@"Parameter does not conform to MyDelegate protocol at line %d", (int)__LINE__];
}

in your delegate accessor (setDelegate) code. This helps minimize mistakes.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

ngModel cannot be used to register form controls with a parent formGroup directive

OK, finally got it working: see https://github.com/angular/angular/pull/10314#issuecomment-242218563

In brief, you can no longer use name attribute within a formGroup, and must use formControlName instead

Lumen: get URL parameter in a Blade view

More simple in Laravel 5.7 and 5.8

{{ Request()->parameter }}

How can I schedule a daily backup with SQL Server Express?

You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:

"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"

How can I detect when an Android application is running in the emulator?

use this function :

 public static final boolean isEmulator() {

    int rating = 0;

    if ((Build.PRODUCT.equals("sdk")) || (Build.PRODUCT.equals("google_sdk"))
            || (Build.PRODUCT.equals("sdk_x86")) || (Build.PRODUCT.equals("vbox86p"))) {
        rating++;
    }
    if ((Build.MANUFACTURER.equals("unknown")) || (Build.MANUFACTURER.equals("Genymotion"))) {
        rating++;
    }
    if ((Build.BRAND.equals("generic")) || (Build.BRAND.equals("generic_x86"))) {
        rating++;
    }
    if ((Build.DEVICE.equals("generic")) || (Build.DEVICE.equals("generic_x86")) || (Build.DEVICE.equals("vbox86p"))) {
        rating++;
    }
    if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))
            || (Build.MODEL.equals("Android SDK built for x86"))) {
        rating++;
    }
    if ((Build.HARDWARE.equals("goldfish")) || (Build.HARDWARE.equals("vbox86"))) {
        rating++;
    }
    if ((Build.FINGERPRINT.contains("generic/sdk/generic"))
            || (Build.FINGERPRINT.contains("generic_x86/sdk_x86/generic_x86"))
            || (Build.FINGERPRINT.contains("generic/google_sdk/generic"))
            || (Build.FINGERPRINT.contains("generic/vbox86p/vbox86p"))) {
        rating++;
    }

    return rating > 4;

    }

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

setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.

depending on the number of iterations, performance difference will likely be negligible.

However i agree with the others that having it outside the loop make the loop body look cleaner.

If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.

How can I easily add storage to a VirtualBox machine with XP installed?

For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.

http://forums.virtualbox.org/viewtopic.php?f=6&t=22422

As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.

http://gparted.sourceforge.net/download.php

switch case statement error: case expressions must be constant expression

How about this other solution to keep the nice switch instead of an if-else:

private enum LayoutElement {
    NONE(-1),
    PLAY_BUTTON(R.id.playbtn),
    STOP_BUTTON(R.id.stopbtn),
    MENU_BUTTON(R.id.btnmenu);

    private static class _ {
        static SparseArray<LayoutElement> elements = new SparseArray<LayoutElement>();
    }

    LayoutElement(int id) {
        _.elements.put(id, this);
    }

    public static LayoutElement from(View view) {
        return _.elements.get(view.getId(), NONE);
    }

}

So in your code you can do this:

public void onClick(View src) {
    switch(LayoutElement.from(src)) {
    case PLAY_BUTTTON:
        checkwificonnection();
        break;

    case STOP_BUTTON:
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
        break;

    case MENU_BUTTON:
        openOptionsMenu();
        break;
    }
}

Enums are static so this will have very limited impact. The only window for concern would be the double lookup involved (first on the internal SparseArray and later on the switch table)

That said, this enum can also be utilised to fetch the items in a fluent manner, if needed by keeping a reference to the id... but that's a story for some other time.

Creating a new database and new connection in Oracle SQL Developer

  1. Connect to sys.
  2. Give your password for sys.
  3. Unlock hr user by running following query:

alter user hr identified by hr account unlock;

  1. Then, Click on new connection
  2. Give connection name as HR_ORCL Username: hr Password: hr Connection Type: Basic Role: default Hostname: localhost Port: 1521 SID: xe

  3. Click on test and Connect

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

What is the "right" JSON date format?

The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);

How do you attach and detach from Docker's process?

If you only need the docker process to go in the background you can use

Ctrl + Z

Be aware that it is not a real detach and it comes with a performance penalty. (You can return it to foreground with the bg command).

Another option is to just close your terminal, if you don't need it any longer.

Button Width Match Parent

you can do that wit MaterialButton

MaterialButton(
     padding: EdgeInsets.all(12.0),
     minWidth: double.infinity,
     onPressed: () {},
    child: Text("Btn"),
)

onchange equivalent in angular2

You can use:

<input (input)="saverange()>

How to check internet access on Android? InetAddress never times out

public class Network {

Context context;

public Network(Context context){
    this.context = context;
}

public boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();
}

}

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

The data type TEXT is old and should not be used anymore, it is a pain to select data out of a TEXT column.

ntext, text, and image (Transact-SQL)

ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

you need to use TEXTPTR (Transact-SQL) to retrieve the text data.

Also see this article on Handling The Text Data Type.

What are the rules for casting pointers in C?

You have a pointer to a char. So as your system knows, on that memory address there is a char value on sizeof(char) space. When you cast it up to int*, you will work with data of sizeof(int), so you will print your char and some memory-garbage after it as an integer.

JPA EntityManager: Why use persist() over merge()?

Scenario X:

Table:Spitter (One) ,Table: Spittles (Many) (Spittles is Owner of the relationship with a FK:spitter_id)

This scenario results in saving : The Spitter and both Spittles as if owned by Same Spitter.

        Spitter spitter=new Spitter();  
    Spittle spittle3=new Spittle();     
    spitter.setUsername("George");
    spitter.setPassword("test1234");
    spittle3.setSpittle("I love java 2");       
    spittle3.setSpitter(spitter);               
    dao.addSpittle(spittle3); // <--persist     
    Spittle spittle=new Spittle();
    spittle.setSpittle("I love java");
    spittle.setSpitter(spitter);        
    dao.saveSpittle(spittle); //<-- merge!!

Scenario Y:

This will save the Spitter, will save the 2 Spittles But they will not reference the same Spitter!

        Spitter spitter=new Spitter();  
    Spittle spittle3=new Spittle();     
    spitter.setUsername("George");
    spitter.setPassword("test1234");
    spittle3.setSpittle("I love java 2");       
    spittle3.setSpitter(spitter);               
    dao.save(spittle3); // <--merge!!       
    Spittle spittle=new Spittle();
    spittle.setSpittle("I love java");
    spittle.setSpitter(spitter);        
    dao.saveSpittle(spittle); //<-- merge!!

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

This is possible using this cross browser javascript implementation of the HTML5 saveAs function: https://github.com/koffsyrup/FileSaver.js

If all you want to do is save text then the above script works in all browsers(including all versions of IE), using nothing but JS.

Angular2 Material Dialog css, dialog size

You can also let angular material solve the size itself depending on the content. This means you don't have to cloud your TS files with sizes that depend on your UI. You can keep these in the HTML/CSS.

my-dialog.html

<div class="myContent">
  <h1 mat-dialog-title fxLayoutAlign="center">Your title</h1>
  <form [formGroup]="myForm" fxLayout="column">
    <div mat-dialog-content>
    </div mat-dialog-content>
  </form>
</div>

my-dialog.scss

.myContent {
    width: 300px;
    height: 150px;
}

my-component.ts

const myInfo = {};
this.dialog.open(MyDialogComponent, { data: myInfo });

External resource not being loaded by AngularJs

Had the same issue here. I needed to bind to Youtube links. What worked for me, as a global solution, was to add the following to my config:

.config(['$routeProvider', '$sceDelegateProvider',
        function ($routeProvider, $sceDelegateProvider) {

    $sceDelegateProvider.resourceUrlWhitelist(['self', new RegExp('^(http[s]?):\/\/(w{3}.)?youtube\.com/.+$')]);

}]);

Adding 'self' in there is important - otherwise will fail to bind to any URL. From the angular docs

'self' - The special string, 'self', can be used to match against all URLs of the same domain as the application document using the same protocol.

With that in place, I'm now able to bind directly to any Youtube link.

You'll obviously have to customise the regex to your needs. Hope it helps!

Force index use in Oracle

If you think the performance of the query will be better using the index, how could you force the query to use the index?

First you would of course verify that the index gave a better result for returning the complete data set, right?

The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:

select /*+ index(table_name (column_having_index)) */ *
from   table_name
where  column_having_index="some value"; 

In more complex cases you might ...

select /*+ index(t (t.column_having_index)) */ *
from   my_owner.table_name t,
       ...
where  t.column_having_index="some value"; 

With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.

How do I make a redirect in PHP?

You can attempt to use the PHP header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

ob_start();
header("Location: " . $website);
ob_end_flush();

ssh_exchange_identification: Connection closed by remote host under Git bash

Got the same error message. Turning off WiFi and turning it back on again worked for me.

How to get the input from the Tkinter Text Widget?

Here is how I did it with python 3.5.2:

from tkinter import *
root=Tk()
def retrieve_input():
    inputValue=textBox.get("1.0","end-1c")
    print(inputValue)

textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit", 
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()

mainloop()

with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https

Color a table row with style="color:#fff" for displaying in an email

Try to use the <font> tag

?<table> 
    <thead> 
        <tr> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

But I think this should work, too:

?<table> 
    <thead> 
        <tr> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

EDIT:

Crossbrowser solution:

use capitals in HEX-color.

<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>

Sublime Text 3 how to change the font size of the file sidebar?

If you are using the default theme. Just goto Preferences-> Default File Preferences A new tab pops up. At about line number you could see the font [font-name] [font-size]

Edit the font-size according to your wish and save.

What does "for" attribute do in HTML <label> tag?

The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)

In the first example in the question (without the for), the use of label markup has no logical or functional implication – it’s useless, unless you do something with it in CSS or JavaScript.

HTML specifications do not make it mandatory to associate labels with controls, but Web Content Accessibility Guidelines (WCAG) 2.0 do. This is described in the technical document H44: Using label elements to associate text labels with form controls, which also explains that the implicit association (by nesting e.g. input inside label) is not as widely supported as the explicit association via for and id attributes,

In android how to set navigation drawer header image and name programmatically in class file?

If you're using bindings you can do

val headerView = binding.navView.getHeaderView(0)
val headerBinding = NavDrawerHeaderBinding.bind(headerView)
headerBinding.textView.text = "Your text here"

OWIN Startup Class Missing

If you don't want to use the OWIN startup, this is what you should add to your web.config file:

Under AppSettings add the following line:

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

This is how it should look like in your web.config:

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

How to install pywin32 module in windows 7

Quoting the README at https://github.com/mhammond/pywin32:

By far the easiest way to use pywin32 is to grab binaries from the most recent release

Just download the installer for your version of Python from https://github.com/mhammond/pywin32/releases and run it, and you're done.

Benefits of EBS vs. instance-store (and vice-versa)

Eric pretty much nailed it. We (Bitnami) are a popular provider of free AMIs for popular applications and development frameworks (PHP, Joomla, Drupal, you get the idea). I can tell you that EBS-backed AMIs are significantly more popular than S3-backed. In general I think s3-backed instances are used for distributed, time-limited jobs (for example, large scale processing of data) where if one machine fails, another one is simply spinned up. EBS-backed AMIS tend to be used for 'traditional' server tasks, such as web or database servers that keep state locally and thus require the data to be available in the case of crashing.

One aspect I did not see mentioned is the fact that you can take snapshots of an EBS-backed instance while running, effectively allowing you to have very cost-effective backups of your infrastructure (the snapshots are block-based and incremental)