text:
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<title>TEST PAGE</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="nav.css">
    <link rel="stylesheet" type="text/css" href="calendar/calendar.css">
    <link rel="stylesheet" type="text/css" href="test.css">
    <link rel="stylesheet" type="text/css" href="admin.css">

Home

Search

About

Upload

<?php

//start session to check that the person has signed in
session_start();

//do check if the person is logged in and if they are show the uploaded_data table for them to be verified and copied to live_data
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['accessLevel'] == 'admin'){
    echo "
Admin
";
    echo "
". $_SESSION['username']."
";
}
?>

Login

<form method="post" action="search_display.php">
<input class="search" type="text" name="subject" placeholder="Search..">
<button class="search"></button>
</form>

<form>
<textarea rows="8" cols="60">
</textarea>
<button>POST</button>
</form>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.rave.portal.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.rave.model.PageType;
import org.apache.rave.model.Person;
import org.apache.rave.model.User;
import org.apache.rave.rest.model.SearchResult;
import org.apache.rave.portal.repository.CategoryRepository;
import org.apache.rave.portal.repository.PageRepository;
import org.apache.rave.portal.repository.PageTemplateRepository;
import org.apache.rave.portal.repository.PersonRepository;
import org.apache.rave.portal.repository.UserRepository;
import org.apache.rave.portal.repository.WidgetRepository;
import org.apache.rave.portal.service.EmailService;
import org.apache.rave.portal.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service(value = "userService")
public class DefaultUserService implements UserService {
    private static final Logger log = LoggerFactory.getLogger(DefaultUserService.class);

    private final UserRepository userRepository;
    private final PageRepository pageRepository;
    private final PageTemplateRepository pageTemplateRepository;
    private final WidgetRepository widgetRepository;
    private final CategoryRepository categoryRepository;
    private final PersonRepository personRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private EmailService emailService;

    @Value("${portal.mail.passwordservice.subject}")
    private String passwordReminderSubject;

    @Value("${portal.mail.passwordservice.template}")
    private String passwordReminderTemplate;

    @Value("${portal.mail.username.subject}")
    private String userNameReminderSubject;

    @Value("${portal.mail.username.template}")
    private String userNameReminderTemplate;

    @Value("${portal.mail.service.baseurl}")
    private String baseUrl;

    @Value("${portal.user.account.admin.subject}")
    private String userAccountApprovalSubject;

    @Value("${portal.user.account.admin.template}")
    private String userAccountApprovalTemplate;

    @Value("${portal.user.account.needapproval}")
    private boolean userAccountApproval;

    @Value("${portal.user.account.admin.email}")
    private String approvalAdminEmail;

    @Value("${portal.mail.service.loginpage}")
    private String loginUrl;

    @Autowired
    public DefaultUserService(PageRepository pageRepository,
                              UserRepository userRepository,
                              WidgetRepository widgetRepository,
                              PageTemplateRepository pageTemplateRepository,
                              CategoryRepository categoryRepository,
                              PersonRepository personRepository) {
        this.userRepository = userRepository;
        this.pageRepository = pageRepository;
        this.widgetRepository = widgetRepository;
        this.pageTemplateRepository = pageTemplateRepository;
        this.categoryRepository = categoryRepository;
        this.personRepository = personRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        log.debug("loadUserByUsername called with: {}", username);
        final User user = userRepository.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User with username '" + username + "' was not found!");
        }
        return user;
    }

    @Override
    public User getAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return (User) authentication.getPrincipal();
        } else {
            throw new SecurityException("Could not get the authenticated user!");
        }
    }

    @Override
    public void setAuthenticatedUser(String userId) {
        final User user = userRepository.get(userId);
        if (user == null) {
            throw new UsernameNotFoundException("User with id '" + userId + "' was not found!");
        }
        SecurityContext securityContext = createContext(user);
        SecurityContextHolder.setContext(securityContext);
    }

    @Override
    public void clearAuthenticatedUser() {
        SecurityContextHolder.clearContext();
    }

    private SecurityContext createContext(final User user) {
        SecurityContext securityContext = new SecurityContextImpl();
        securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) {
            private static final long serialVersionUID = 1L;

            @Override
            public Object getCredentials() {
                return "N/A";
            }

            @Override
            public Object getPrincipal() {
                return user;
            }

            @Override
            public boolean isAuthenticated() {
                return true;
            }
        });
        return securityContext;
    }

    @Override
    @Transactional
    public void registerNewUser(User user) {
    	if(userAccountApproval){
    		user.setEnabled(false);
    	}
        User managedUser = userRepository.save(user);
        pageRepository.createPageForUser(managedUser, pageTemplateRepository.getDefaultPage(PageType.PERSON_PROFILE.toString()));
        if(userAccountApproval && !approvalAdminEmail.isEmpty()){
            Map<String, Object> templateData = new HashMap<String, Object>();
            templateData.put("user", user);
            templateData.put("portalUrl", loginUrl);
        	emailService.sendEmail(approvalAdminEmail, userAccountApprovalSubject, userAccountApprovalTemplate, templateData);
    	}
    }

    @Override
    public User getUserById(String id) {
        return userRepository.get(id);
    }

    @Override
    public User getUserByUsername(String userName) {
        return userRepository.getByUsername(userName);
    }

    @Override
    public User getUserByEmail(String userEmail) {
        return userRepository.getByUserEmail(userEmail);
    }

    @Override
    public User getUserByOpenId(String openId) {
        return userRepository.getByOpenId(openId);
    }

    @Override
    @Transactional
    public void updateUserProfile(User user) {
        userRepository.save(user);
    }

    @Override
    public SearchResult<User> getAll() {
        final int count = userRepository.getCountAll();
        final List<User> users = userRepository.getAll();
        return new SearchResult<User>(users, count);
    }

    @Override
    public SearchResult<User> getLimitedList(int offset, int pageSize) {
        final int count = userRepository.getCountAll();
        final List<User> users = userRepository.getLimitedList(offset, pageSize);
        final SearchResult<User> searchResult = new SearchResult<User>(users, count);
        searchResult.setOffset(offset);
        searchResult.setPageSize(pageSize);
        return searchResult;
    }

    @Override
    public SearchResult<Person> getLimitedListOfPersons(int offset, int pageSize) {
        SearchResult<User> users = getLimitedList(offset, pageSize);
        int count = users.getTotalResults();
        List<Person> people = new ArrayList<Person>();
        Person person = null;
        for(User user : users.getResultSet()){
            person = user.toPerson();
            person.setId(user.getId());
            people.add(person);
        }
        return new SearchResult<Person>(people, count);
    }

    @Override
    public SearchResult<User> getUsersByFreeTextSearch(String searchTerm, int offset, int pageSize) {
        final int count = userRepository.getCountByUsernameOrEmail(searchTerm);
        final List<User> users = userRepository.findByUsernameOrEmail(searchTerm, offset, pageSize);
        final SearchResult<User> searchResult = new SearchResult<User>(users, count);
        searchResult.setOffset(offset);
        searchResult.setPageSize(pageSize);
        return searchResult;
    }

    @Override
    public SearchResult<Person> getPersonsByFreeTextSearch(String searchTerm, int offset, int pageSize) {
        SearchResult<User> users = getUsersByFreeTextSearch(searchTerm, offset, pageSize);
        int count = users.getTotalResults();
        List<Person> people = new ArrayList<Person>();
        Person person = null;
        for(User user : users.getResultSet()){
            person = user.toPerson();
            person.setId(user.getId());
            people.add(person);
        }
        return new SearchResult<Person>(people, count);
    }

    @Override
    @Transactional
    // TODO RAVE-300: add security check that is is called by admin or the user itself
    public void deleteUser(String userId) {
        log.info("about to delete userId: " + userId);
        User user = userRepository.get(userId);
        if (user == null) {
            log.warn("unable to find userId " + userId + " to delete");
            return;
        }

        final String username = user.getUsername();

        // delete all User type pages
        int numDeletedPages = pageRepository.deletePages(userId, PageType.USER.toString());
        // delete all person pages
        int numDeletedPersonPages = pageRepository.deletePages(userId, PageType.PERSON_PROFILE.toString());
        // delete all the widget comments
        int numWidgetComments = widgetRepository.deleteAllWidgetComments(userId);
        // delete all the widget ratings
        int numWidgetRatings = widgetRepository.deleteAllWidgetRatings(userId);
        // unassign the user from any widgets where they were the owner
        int numWidgetsOwned = widgetRepository.unassignWidgetOwner(userId);
        // unassign the user from any category records they created or modified
        int numCategoriesTouched = categoryRepository.removeFromCreatedOrModifiedFields(userId);
        // remove any person associations created with other users
        int numAssociationsRemoved = personRepository.removeAllFriendsAndRequests(userId);

        // finally delete the user
        userRepository.delete(user);
        log.info("Deleted user [" + userId + ',' + username + "] - numPages: " + numDeletedPages + ", numPersonPages:" +
                 numDeletedPersonPages + ", numWidgetComments: " + numWidgetComments + ", numWidgetRatings: " +
                 numWidgetRatings + ", numWidgetsOwned: " + numWidgetsOwned + ", numCategoriesTouched:" + numCategoriesTouched +
                 ", numAssociationRemoved:" + numAssociationsRemoved);
    }

    @Override
    public List<Person> getAllByAddedWidget(String widgetId) {
        List<Person> persons = new ArrayList<Person>();
        List<User> users = userRepository.getAllByAddedWidget(widgetId);
        for (User u : users) {
            persons.add(u.toPerson());
        }
        return persons;
    }

    @Override
    public void updatePassword(User newUser) {
        log.debug("Changing password  for user {}", newUser);
        User user = userRepository.getByForgotPasswordHash(newUser.getForgotPasswordHash());
        if (user == null) {
            throw new IllegalArgumentException("Could not find user for forgotPasswordHash " + newUser.getForgotPasswordHash());
        }
        String saltedHashedPassword = passwordEncoder.encode(newUser.getPassword());
        user.setPassword(saltedHashedPassword);
        // reset password hash and time
        user.setForgotPasswordHash(null);
        user.setForgotPasswordTime(null);
        userRepository.save(user);

    }

    @Override
    public void sendUserNameReminder(User newUser) {
        log.debug("Calling send username  {}", newUser);
        User user = userRepository.getByUserEmail(newUser.getEmail());
        if (user == null) {
            throw new IllegalArgumentException("Could not find user for email " + newUser.getEmail());
        }
        String to = user.getUsername() + " <" + user.getEmail() + '>';
        Map<String, Object> templateData = new HashMap<String, Object>();
        templateData.put("user", user);
        emailService.sendEmail(to, userNameReminderSubject, userNameReminderTemplate, templateData);

    }

    @Override
    public void sendPasswordReminder(User newUser) {
        log.debug("Calling send password change link for user {}", newUser);
        User user = userRepository.getByUserEmail(newUser.getEmail());
        if (user == null) {
            throw new IllegalArgumentException("Could not find user for email " + newUser.getEmail());
        }
        // create user hash:
        String input = user.getEmail() + user.getUsername() + String.valueOf(user.getId()) + System.nanoTime();
        // hash needs to be URL friendly:
        String safeString = new String(Base64.encode(passwordEncoder.encode(input).getBytes()));
        String  hashedInput = safeString.replaceAll("[/=]", "A");
        user.setForgotPasswordHash(hashedInput);
        user.setForgotPasswordTime(Calendar.getInstance().getTime());
        userRepository.save(user);
        String to = user.getUsername() + " <" + user.getEmail() + '>';
        Map<String, Object> templateData = new HashMap<String, Object>();
        templateData.put("user", user);
        templateData.put("reminderUrl", baseUrl + hashedInput);
        emailService.sendEmail(to, passwordReminderSubject, passwordReminderTemplate, templateData);
    }

    @Override
    public boolean isValidReminderRequest(String forgotPasswordHash, int nrOfMinutesValid) {
        if (StringUtils.isBlank(forgotPasswordHash)) {
            return false;
        }

        User userForHash = userRepository.getByForgotPasswordHash(forgotPasswordHash);
        if (userForHash == null) {
            return false;
        }
        Date requestTime = userForHash.getForgotPasswordTime();
        Calendar expiredDate = Calendar.getInstance();
        expiredDate.add(Calendar.MINUTE, nrOfMinutesValid);

        if (requestTime == null || requestTime.after(expiredDate.getTime())) {
            // reset,  this is invalid state
            userForHash.setForgotPasswordHash(null);
            userForHash.setForgotPasswordTime(null);
            userRepository.save(userForHash);
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean addFriend(String friendUsername, String username) {
    	return personRepository.addFriend(friendUsername,username);
    }

    @Override
    @Transactional
    public void removeFriend(String friendUsername, String username) {
    	personRepository.removeFriend(friendUsername,username);
    }

    @Override
    public HashMap<String, List<Person>> getFriendsAndRequests(String username) {
    	return personRepository.findFriendsAndRequests(username);
    }

	@Override
	public List<Person> getFriendRequestsReceived(String username) {
		return personRepository.findFriendRequestsReceived(username);
	}

    @Override
    @Transactional
    public boolean acceptFriendRequest(String friendUsername, String username) {
    	return personRepository.acceptFriendRequest(friendUsername,username);
    }

	@Override
	public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {
		final String openId = token.getIdentityUrl();
		User user = this.getUserByOpenId(openId);
		if (user == null) {
			log.info("Open ID User with URL "+openId+" was not found!");
			throw new UsernameNotFoundException("Open ID User with URL "+openId+" was not found!");
		}
		return user;
	}
}


text:
using MJennings.Caching;
using MJennings.Logging;
using System;
using System.IO;
using System.Threading;
using System.Linq;
using Xunit;

namespace MJennings.Common.Tests.Caching
{
    public class MemoryCacheTests : CachingTestsBase
    {
        [Fact]
        public void SetItem_WithExpiration_ShouldSetAndExpire()
        {
            var cache = new MemoryCache();

            cache.ItemExpired +=
                delegate (object sender, CacheItemExpiredEventArgs e)
                {
                    Logger.Log(new LogEntry { Message = "Cache Item Expired A - " + e.ItemKey });
                };

            var guid = Guid.NewGuid().ToString();
            var name = "Cache Item Name - " + guid;
            var value = "Cache Item Value - " + guid;

            Logger.Log(new LogEntry { Message = "Adding item to cache - " + name });

            cache.SetItem(name, value, TimeSpan.FromMilliseconds(1000),
                delegate (object sender, CacheItemExpiredEventArgs e)
                {
                    Logger.Log(new LogEntry { Message = "Cache Item Expired B - " + e.ItemKey });
                });

            Logger.Log(new LogEntry { Message = "Item added to cache - " + name });

            Assert.True(cache.ContainsItem(name));
            Assert.Equal(value, cache.GetItem<string>(name));
            Logger.Log(new LogEntry { Message = "Sleeping - " + name });
            Thread.Sleep(3000);
            Logger.Log(new LogEntry { Message = "Waking up - " + name });
            Assert.Null(cache.GetItem<string>(name));

            Logger.Flush();
            Thread.Sleep(1000);

            var loggerLines = File.ReadAllLines(Logger.LogFile.FullName).Where(line => line.IndexOf(guid, StringComparison.OrdinalIgnoreCase) >= 0);
            Assert.True(loggerLines.Count() > 0);
            File.Delete(Logger.LogFile.FullName);
        }
    }
}


text:
package org.spongepowered.common.mixin.bungee.network;

import com.mojang.authlib.properties.Property;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.network.NetworkManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.bridge.network.NetworkManagerBridge;
import org.spongepowered.common.bridge.network.NetworkManagerBridge_Bungee;

import java.net.SocketAddress;
import java.util.UUID;

@SuppressWarnings("rawtypes")
@Mixin(NetworkManager.class)
public abstract class NetworkManagerMixin_Bungee extends SimpleChannelInboundHandler implements NetworkManagerBridge_Bungee {

    @Shadow private SocketAddress socketAddress;

    private UUID impl$spoofedUUID;
    private Property[] impl$spoofedProfile;

    @Override
    public void bungeeBridge$setRemoteAddress(final SocketAddress socketAddress) {
        this.socketAddress = socketAddress;
    }

    @Override
    public UUID bungeeBridge$getSpoofedUUID() {
        return this.impl$spoofedUUID;
    }

    @Override
    public void bungeeBridge$setSpoofedUUID(final UUID uuid) {
        this.impl$spoofedUUID = uuid;
    }

    @Override
    public Property[] bungeeBridge$getSpoofedProfile() {
        return this.impl$spoofedProfile;
    }

    @Override
    public void bungeeBridge$setSpoofedProfile(final Property[] profile) {
        this.impl$spoofedProfile = profile;
    }
}


text:
import nock from 'nock';
import expect from 'expect';
import mockStore from '../../helpers/mockStore';
import env from '../../../../frontend/src/lib/env';
import * as constants from '../../../../frontend/src/constants/transactions';
import fetchByGroup from '../../../../frontend/src/actions/transactions/fetch_by_group';

describe('transactions/fetch_by_group actions', () => {

  afterEach(() => nock.cleanAll());
  const options = {};

  it('creates TRANSACTIONS_SUCCESS if it fetches successfully', (done) => {
    const transaction = {
      id: 2,
      amount: 999
    };
    const slug = 'testgroup';

    nock(env.API_ROOT)
      .get(`/groups/${slug}/transactions`)
      .reply(200, [transaction]);

    const store = mockStore({});

    store.dispatch(fetchByGroup(slug))
    .then(() => {
      const [request, success] = store.getActions();
      expect(request).toEqual({ type: constants.TRANSACTIONS_REQUEST, slug, options })
      expect(success).toEqual({ type: constants.TRANSACTIONS_SUCCESS, slug, transactions: [ transaction ] })
      done();
    })
    .catch(done)
  });

  it('creates TRANSACTIONS_FAILURE if it fails', (done) => {
    const slug = 1;

    nock(env.API_ROOT)
      .get(`/groups/${slug}/transactions`)
      .replyWithError('');

    const store = mockStore({});

    store.dispatch(fetchByGroup(slug))
    .then(() => {
      const [request, failure] = store.getActions();
      expect(request).toEqual({ type: constants.TRANSACTIONS_REQUEST, slug, options });
      expect(failure.type).toEqual(constants.TRANSACTIONS_FAILURE);
      expect(failure.error.message).toContain('request to http://localhost:3000/api/groups/1/transactions failed');
      done();
    })
    .catch(done)
  });

});


text:
namespace qrw {

class GuiCamera : public Camera
{
public:
    GuiCamera();

    virtual ~GuiCamera();

    virtual void applyTo(sf::RenderTarget& renderTarget) override;

private:
    GuiCamera(const GuiCamera& rhs) = delete;

    GuiCamera& operator=(const GuiCamera& rhs) = delete;
};

} // namespace qrw

#endif // QRW_GUICAMERA_HPP


text:
layout: post
cover: false
title: Code formatting and RxJS
date:   2017-09-08
subclass: 'post'
categories: 'casper'
published: true
disqus: true
---

One of the main benefits of RxJS to me is that it provides code that is 'readable'. It provides us with a declarative programming approach where implementation details are hidden away. We are just describing what needs to be done, not how it should be done. This makes code you look at easy to understand.

One problem that I face regularly when looking at other peoples code is that the code formatting or the way the (RxJS) code is written, takes away part of the benefit of writing your code this way. This post is a small summary on how I like to format my code to keep the readability benefits to a maximum.

### One operator per line

One thing I see all the time is something like this:

```typescript
Rx.Observable.interval(1000).map(x => x*2).filter(x => x%2 === 0)
	.mergeMap(x => someBackendCall(x)).map(res => res.json()).subscribe();
```

Here we can see a simple stream. Looking at what is does is a little more difficult however because of the outlining of the operators. If you format the code like this, it makes it so much easier:

```typescript
Rx.Observable.interval(1000)
	.map(x => x*2)
	.filter(x => x%2 === 0)
	.mergeMap(x => someBackendCall(x))
	.map(res => res.json())
	.subscribe();
```

By putting every operator on a new line, it is so much easier to see what's happening.

### Using nested functions for functions longer than one line

A lot of the RxJS operators will accept functions as parameters. These functions can influence the code formatting and impair the readability. Let's take a look at an example:

```typescript
// A data$ stream
private data$: Observable<Array<Data>>;

// A function that uses this data$
doSomething() {
    this.data$
    	.take(1)
        .map((data) => {
            if (data && data.length > 0) {
                	return data.forEach(datum => {
                    datum.active = false;
                	});
            } else {
            		return [];
            }
        })
        .mergeMap((data) => {
            data.forEach(datum => {
                this.whateverService.update(data);
            });
        })
        .subscribe();
}
```

We have a function `doSomething()` that, when called, will use the `data$` stream as a source and will perform a mapping of the data array events inside of this stream and then will perform a backend call for every element inside this array.
If you were able to detect this immediately, my hat off to you. To me however, this looks pretty bad. Let's take a look at how we could make this better:

```typescript
// A data$ stream
private data$: Observable<Array<Data>>;

// A function that uses this data$
doSomething() {
    const mapAllTheElementsActiveFlagToFalse = (data) => {
        if (data && data.length > 0) {
            return data.forEach(datum => {
                datum.active = false;
            });
        } else {
            return [];
        }
    };

    const callTheWhateverServiceForEveryElement = (data) => {
        data.forEach(datum => {
            this.whateverService.update(data);
        });
    };

    this.data$
    	.take(1)
        .map(mapAllTheElementsActiveFlagToFalse)
        .mergeMap(callTheWhateverServiceForEveryElement)
        .subscribe();
}
```

I updated the code so that all the functions passed to the operators are first created as nested functions. This might feel a little weird at first, creating nested functions, but if we look at the last few lines of code, these have become so much cleaner. If you know what the operators of RxJS do, you can actually read what is happening (I must admit, naming these functions might not be my strongest feat :)). You only have to look at the last lines of this function. The implementation details of the nested functions is irrelevant (remember, declarative is easier to read).
I find this approach really helpful and tend to use it a lot, especially for functions that are longer than a single line.

### Avoid using nested observables

RxJS provides us with a lot of operators which you can do a whole range of stuff with. One of them is combining different streams. One thing I sometimes see is this:

```typescript
private data$: Observable<Array<Data>>;
private data2$: Observable<Data2>;

result$: Observable<any>;

doSomething() {
	 // we combine the data$ and data2$ with combineLatest
    this.result$ = Observable.combineLatest(
        this.data$
            .map(data => data.length),
        this.data2$
            .mergeMap(val => this.whateverService.call(val)),
        (val1, val2) => {
            // handle the values here
        }
    );
}
```

We create an observable by using the `combineLatest` operator. But before we do so, the `data$` and `data2$` streams are transformed. You could say we are working with nested streams. And even though, the operators are aligned perfectly and there are no functions that are longer than one line, it still feels weird. Let's see how we might be able to make it better:

```typescript
private data$: Observable<Array<Data>>;
private data2$: Observable<Data2>;

result$: Observable<any>;

doSomething() {
    const dataLength$ = this.data$
        .map(data => data.length);
    const whateverData$ = this.data2$
        .mergeMap(val => this.whateverService.call(val));

	 // we combine the data$ and data2$ with combineLatest
    this.result$ = Observable.combineLatest(
        dataLength$,
        whateverData$,
        (val1, val2) => {
            // handle the values here
        }
    );
}
```

This time, I extracted the nested observables and matched them to local variables first. I then use these newly created local variables to create a new stream using the `combineLatest` operator.
By extracting nested observables to a separate variable and naming this new observable properly, the code is easier to understand.

**Conclusion**

Try to keep the following in mind when writing RxJS code:

1. Put every operator on a new line.
2. Extract functions longer than a line to a nested function.
3. Try to avoid working with nested observables.


text:
@interface ClockTime : NSObject {

}

@property (nonatomic, readonly) NSUInteger minutes;
@property (nonatomic, readonly) NSUInteger seconds;
@property (nonatomic, readonly) NSUInteger totalSeconds;

+ (ClockTime *) timeWithMinutes:(NSUInteger)min;
+ (ClockTime *) timeWithMinutes:(NSUInteger)min seconds:(NSUInteger)sec;

- (id) initWithMinutes:(NSUInteger)min seconds:(NSUInteger)sec;

- (BOOL) isExpired;

- (NSString *) string;
- (NSString *) stringLabeled;

- (id) timeDecremented;

- (id) timeWithMinutes:(NSUInteger)min;

- (id) timeWithSeconds:(NSUInteger)sec;

@end


text:
title: Follow the trail…….Join the Concurrency Revolution !!!
author: vivekragunathan
layout: post
date: 2006-12-20T17:50:00+00:00
url: /2006/12/20/follow-the-trail-join-the-concurrency-revolution/
categories:
  - CodeProject
  - Uncategorized

---

I could not stop writing this post after I read [**this**](http://www.gotw.ca/publications/guest-ed-200609.htm) article by Herb Sutter. The article is just a casual technical discussion but very encouraging that a person requires at the right time – the time when he is a student. Even after several years after my college, I have been trying to keep myself a student and I got a right encouragement to join the Concurrency revolution. Thanks to Herb Sutter.

As Albert Einstein, Robert Goddard, and Wernher von Braun walked the trail of Galileo and Newton , I will to walk the trail of some of the contemporary people like Sutter, Stroustoup, Don Box, Richter and others.


text:
package com.mckoi.odb;

/**
 * A class in the Mckoi Object database data model. The class object
 * describes either a system primitive type, or a used defined class
 * specification. A class specification is a number of named fields and their
 * corresponding type that make up the fields in an object instance.
 * <p>
 * A class object is immutable and has a corresponding reference to the
 * class object in the storage medium.
 *
 * @author Tobias Downer
 */

public interface ODBClass extends ODBReferenced {

  /**
   * Returns the name of this class.
   */
  String getName();

  /**
   * Returns the instance name of this class, which is a globally unique
   * identifier used to resolve the class details against the object
   * database.
   */
  String getInstanceName();

  /**
   * Returns the number of fields defined for this class.
   */
  int getFieldCount();

  /**
   * Returns the name of field n.
   */
  String getFieldName(int n);

  /**
   * Returns a string describing the type of field n, which is either;
   * "[S", "$Data", "$String", "$List", "$Class",
   * "[Class Name]#[UID]". All of these identifiers represent references
   * except for "[S" that indicates an inline string. For
   * "[Class Name]#[UID]" types, the "[Class Name]#[UID]" part
   * describes the name of the user class and the reference of the object
   * stored.
   */
  String getFieldType(int n);

  /**
   * Returns true if the field is mutable, false if immutable. A mutable
   * field may be changed in an instance of the class. However a
   * mutable field may not be indexed in an object collection class (only
   * immutable values may be used in an index).
   */
  boolean isFieldMutable(int n);

  /**
   * Returns the index of the field with the given name.
   */
  int indexOfField(String field_name);

}


text:
const webpack = require('webpack'),
      argv    = require('yargs').argv,
      config  = require('../../config'),
      WebpackDevServer = require('webpack-dev-server'),
      makeCompiler = require('../webpack/client');

const QUIET_MODE = !!argv.quiet;

const server = new WebpackDevServer(webpack(makeCompiler()), {
  contentBase : config.inProject(config.SRC_DIRNAME),
  hot    : true,
  quiet  : QUIET_MODE,
  noInfo : QUIET_MODE,
  lazy   : false,
  stats  : {
    colors : true
  },
  historyApiFallback : true
});

server.listen(config.WEBPACK_PORT, config.WEBPACK_HOST, function () {
  console.log('Webpack dev server running at host %s and port %d \n', config.WEBPACK_HOST, config.WEBPACK_PORT);
});

module.exports = exports = server;


text:
require 'spec_helper'
require 'jpm/catalog'
require 'jpm/errors'

describe JPM::Catalog do
  let(:catalog) { described_class.new }

  describe '#current?' do
  end

  describe '#update!' do
  end

  describe '#<<' do
    subject(:add!) { catalog << plugin }

    context 'without a JPM::Plugin argument' do
      let(:plugin) { nil }
      it 'should raise an error' do
        expect { add! }.to raise_error(ArgumentError)
      end
    end

    context' with a JPM::Plugin' do
      let(:plugin) { JPM::Plugin.new }

      it 'should return itself' do
        expect(add!).to eql(catalog)
      end

      it 'should add the plugin properly' do
        expect(catalog.plugins.size).to eql(0)
        add!
        expect(catalog.plugins.size).to eql(1)
      end
    end
  end

  describe '#search' do
    subject(:search) { catalog.search(term) }
  end

  describe '#compute' do
    let(:fixture) { File.expand_path(File.dirname(__FILE__) + '/fixtures/update-center.json') }
    let(:catalog) { described_class.from_file(fixture) }
    subject(:computed_list) { catalog.compute(plugins) }

    context 'with an empty or nil argument' do
      let(:plugins) { [] }
      it { is_expected.to be_empty }
    end

    context 'with a plugin which has no dependencies' do
      let(:plugins) { ['greenballs'] }

      it { is_expected.not_to be_empty }
      its(:size) { should eql 1 }

      it 'should have an instance of JPM::Plugin<greenballs>' do
        plugin = computed_list.first
        expect(plugin).to be_instance_of JPM::Plugin
        expect(plugin.name).to eql 'greenballs'
      end
    end

    context 'with a plugin which has dependencies' do
      # Depends on `credentials`
      let(:plugins) { ['ssh-credentials'] }

      it { is_expected.not_to be_empty }
      its(:size) { should eql 2 }

      it 'should have the right JPM::Plugins computed' do
        expect(computed_list.first).to be_instance_of JPM::Plugin
        expect(computed_list.first.name).to eql 'credentials'
        expect(computed_list.last.name).to eql 'ssh-credentials'
      end
    end

    context 'with a plugin which has nested dependencies' do
      # Depends on ssh-credentials -> credentials
      let(:plugins) { ['git-client'] }

      it { is_expected.not_to be_empty }
      its(:size) { should eql 3 }
    end
  end

  describe '#download' do
    let(:plugin) do
      p = JPM::Plugin.new
      p.name = 'rspec'
      p.url = 'http://rspec.jpi'
      p
    end

    subject(:installation) { catalog.send(:download, plugin) }

    it 'fetch the url from the plugin' do
      response = double('Mock HTTPResponse',
                        :body => '',
                        :code => 200)
      expect(JPM).to receive(:fetch).with(plugin.url).and_return(response)
      expect(catalog).to receive(:save_plugin).and_return(true)

      expect(installation).to be true
    end
  end

  describe '.from_file' do
    subject(:catalog) { described_class.from_file(fixture) }

    context 'with a valid fixtured update-center.json' do
      let(:fixture) { File.expand_path(File.dirname(__FILE__) + '/fixtures/update-center.json') }

      it { is_expected.to be_instance_of described_class }
      # Our fixture file currently has 870 plugins in it
      its(:size) { should eql 870 }
    end

    context 'with an empty update-center.json' do
      let(:fixture) { File.expand_path(File.dirname(__FILE__) + '/fixtures/empty-update-center.json') }

      it 'should raise an error' do
        expect { catalog }.to raise_error(JPM::Errors::InvalidCatalogError)
      end
    end

    context 'with an invalid file path' do
      let(:fixture) { '/rspec/fail' }

      it 'should raise an error' do
        expect { catalog }.to raise_error(JPM::Errors::MissingCatalogError)
      end
    end
  end

end


text:
id: 2177
title: My B.S. in Economics is no match for fist pumping
date: 2010-01-27T07:08:47+00:00
author: Vicki
layout: post
guid: http://blog.vickiboykis.com/wlb/?p=2177
permalink: /2010/01/my-b-s-in-economics-is-no-match-for-fist-pumping/
categories:
  - Uncategorized
tags:
  - economics
  - family
  - i love vinny
  - Jersey Shore
  - me
  - Mr. B
  - professional development
---
Today on Facebook, I was lamenting my life, as usual:

  This comes from my rigorous economic analysis of the recent MTV phenomenon Jersey Shore, which I have been studying every Thursday night at 10:00 pm EST.   The cast members, who, in real life, were working at jobs such as assistant gym manger (The Situation),  a DJ (Pauly D) and a receptionist (Snookie), are now earning a reported $10,000 per appearance, plus security and transportation. Meanwhile, the only thing I get per appearance at my parents’ house is a thorough questioning on why Mr. B and I are not having kids yet.

  STOP.  Are you reading this, having never watched Jersey Shore?   Here’s everything you need to know.

  Back to the economic phenomenon of increased demand for these cast members.  How does this happen?   An astute student of economics breaks it down:

>

>   In December after the show began airing E! Online reports appearance fees of about $7500 per person for The Situation and DJ Pauly D, $2000 plus transportation for Snooki, and about $3500 per person for JWOWW, Vinny, or Ronnie.
>

>
> Now there is a limited supply of Jersey Shore cast members, just 7 (not including Angelina, who ended up being an inferior good). As with normal consumer goods, with a limited supply the price will increase as the scarcity effect occurs when demand increases. Flash forward to January, when the infamous Snooki getting punched in the face at the club scenario occurs. According to Perez Hilton, [**Snooks now takes in $10,000 per appearance**](http://perezhilton.com/2010-01-13-nookis-raking-it-in-post-punch) after the assault! That is 5 times more than her original fee.

  and the post goes on to outline why Snooki was economically elastic after being punched at a club  (meaning that as her price changes, demand changes as well, as opposed to an inelastic good like gasoline, for which demand doesn’t change too much based on price.)

  What have we learned here?

  1.  There needs to be less of me so that I am more in demand for all the jobs I fulfill: consultant, wife, writer, unpregnant daughter, friend, and Edy’s Fruit Bar consumer.   How can I atomize myself so that people will pay  me to appear at not only clubs, but also in my own living room, my computer, and at the Giant grocery store near my house?  I think I will start by informing Mr. B that I will now start appearing in The Kitchen only on certain nights after 10:00 pm for Happy Hour and will only cook on demand.  Also, there will be techno.

  2. Something violent needs to happen to me so that I will emerge into a national sensation and start going on shows with Michael Cera and Rachael Ray.

  3.  I need to stop watching this show and go on with my normal life.


text:
<component name="libraryTable">
  <library name="SBT: org.apache.hadoop:hadoop-mapreduce-client-common:2.4.0:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.hadoop/hadoop-mapreduce-client-common/jars/hadoop-mapreduce-client-common-2.4.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.hadoop/hadoop-mapreduce-client-common/docs/hadoop-mapreduce-client-common-2.4.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.hadoop/hadoop-mapreduce-client-common/srcs/hadoop-mapreduce-client-common-2.4.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>