text:
CAudioScrobbler* AudioScrobbler = 0;

#define CLEANUP()   _response.clear()

size_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)
{
    AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);
    return size*nmemb;
}

CAudioScrobbler::CAudioScrobbler()
{
    _failcount = 0;
    _authed = false;
    _response = "";
    _handle = curl_easy_init();
    if(!_handle) {
        eprintf("%s", "Could not initialize CURL.");
        exit(EXIT_FAILURE);
    }
}

CAudioScrobbler::~CAudioScrobbler()
{
    curl_easy_cleanup(_handle);
    curl_global_cleanup();
}

std::string CAudioScrobbler::GetServiceURL()
{
    if(Config->getService() == LibreFm) {
        return "https://libre.fm/2.0/";
    }
    return "https://ws.audioscrobbler.com/2.0/";
}

void CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)
{
    curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
    curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);
    curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);
    curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);

    if(postfields) {
    curl_easy_setopt(_handle, CURLOPT_POST, 1);
    curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);
    }
    else
    curl_easy_setopt(_handle, CURLOPT_POST, 0);
    if(errbuf)
    curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);

    curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());
    CURLcode res = curl_easy_perform(_handle);

    // Sometimes last.fm likes to just timeout for no reason, leaving us hanging.
    // If this happens, retry a few times with a small delay.
    if (res != CURLE_OK) {
        eprintf("libcurl error (%d): %s", res, curl_easy_strerror(res));
        eprintf("Will retry %d times with a %d second delay.", CURL_MAX_RETRIES, CURL_RETRY_DELAY);

        int retries = 0;
        do {
            sleep(CURL_RETRY_DELAY);
            retries++;
            eprintf("Retry %d/%d", retries, CURL_MAX_RETRIES);

            res = curl_easy_perform(_handle);
            if (res != CURLE_OK) {
                eprintf("Failed: %s", curl_easy_strerror(res));
            }
        } while (res != CURLE_OK && retries < CURL_MAX_RETRIES);
    }
}

void CAudioScrobbler::ReportResponse(char* buf, size_t size)
{
    _response.append(buf);
}

std::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)
{
    const Song& song = entry.getSong();
    std::ostringstream msg, sigmsg ;
    std::string artist, title, album, array = "=";
    std::string songArtist, songTitle;
    char* temp = 0;

    parseSongTitle(song, songArtist, songTitle);

    iprintf("songArtist: %s", songArtist.c_str());
    iprintf("songTitle: %s", songTitle.c_str());

    temp = curl_easy_escape(_handle, songArtist.c_str(), songArtist.length());
    artist = temp;
    curl_free(temp);
    temp = curl_easy_escape(_handle, songTitle.c_str(), songTitle.length());
    title = temp;
    curl_free(temp);
    temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length());
    album = temp;
    curl_free(temp);

    iprintf("%s", artist.c_str());
    iprintf("%s", title.c_str());

    msg << "&album" << array << album;
    msg << "&api_key=" << APIKEY;
    msg << "&artist" << array << artist;
    msg << "&duration" << array << song.getDuration();
    msg << "&method=track.Scrobble";
    msg << "&timestamp" << array << entry.getStartTime();
    msg << "&track" << array << title;
    msg << "&sk=" << _sessionid;

    array = "";

    sigmsg << "album" << array << song.getAlbum();
    sigmsg << "api_key" << APIKEY;
    sigmsg << "artist" << array << songArtist;
    sigmsg << "duration" << array << song.getDuration();
    sigmsg << "methodtrack.Scrobble";
    sigmsg << "sk" << _sessionid;
    sigmsg << "timestamp" << array << entry.getStartTime();
    sigmsg << "track" << array << songTitle;
    sigmsg << SECRET;

    iprintf("%s", sigmsg.str().c_str());

    std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str()));
    msg << "&api_sig=" << sighash;

    iprintf("%s", msg.str().c_str());
    return msg.str();
}

void CAudioScrobbler::Failure()
{
    _failcount += 1;
    if(_failcount >= 3) {
    eprintf("%s", "Re-Handshaking!");
    _failcount = 0;
    Handshake();
    }
}

bool CAudioScrobbler::CheckFailure(std::string response)
{
    bool retval = false;

    size_t start, end;
    start = _response.find("<error code=\"")+13;
    end = _response.find(">", start)-1;
    std::string errorcode = _response.substr(start, end-start);
    int code = strtol(errorcode.c_str(), 0, 10);

    eprintf("%s%i", "Code: ", code);

    switch(code) {
    case 3:
        eprintf("Invalid Method. This should not happen.");
        retval = true;
        break;
    case 4:
        eprintf("Authentication failed. Please check your login data.");
        exit(EXIT_FAILURE);
    case 9:
        eprintf("Invalid session key. Re-authenticating.");
        retval = true;
        _failcount = 3;
        break;
    case 10:
        eprintf("Invalid API-Key. Let's bugger off.");
        exit(EXIT_FAILURE);
    case 13:
        eprintf("Invalid method signature.");
        exit(EXIT_FAILURE);
    case 16:
        eprintf("The service is temporarily unavailable, we will try again later..");
        retval = true;
        break;
    case 26:
        eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm");
        exit(EXIT_FAILURE);
    }

    return retval;
}

bool CAudioScrobbler::Scrobble(const CacheEntry& entry)
{
    bool retval = false;
    if(!_authed) {
    eprintf("Handshake hasn't been done yet.");
    Handshake();
    return retval;
    }
    iprintf("Scrobbling: %s - %s", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());

    OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());
    if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
    iprintf("%s", "Scrobbled successfully.");
    retval = true;
    }
    else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
    eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str());
    if(CheckFailure(_response))
        Failure();
    }
    CLEANUP();

    return retval;
}

bool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)
{
    bool retval = false;

    char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);
    char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);

    std::ostringstream query, sig;
    query << (unlove ? "method=track.unlove&" : "method=track.love&")
    << "&track=" << title
    << "&artist=" << artist
    << "&api_key=" << APIKEY
    << "&sk=" << _sessionid;

    curl_free(artist);
    curl_free(title);

    sig << "api_key" << APIKEY
    << "artist" << song.getArtist()
    << "method" << (unlove ? "track.unlove" : "track.love")
    << "sk" << _sessionid
    << "track" << song.getTitle()
    << SECRET;

    std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

    query << "&api_sig=" << sighash;

    OpenURL(GetServiceURL(), query.str().c_str());

    if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
    iprintf("%s", "(Un)loved track successfully.");
    retval = true;
    }
    else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
    eprintf("%s%s", "Last.fm returned an error while (un)loving the currently playing track:\n", _response.c_str());
    if(CheckFailure(_response))
        Failure();
    }

    CLEANUP();
    return retval;
}

bool CAudioScrobbler::SendNowPlaying(const Song& song)
{
    bool retval = false;

    std::string songArtist, songTitle;
    parseSongTitle(song, songArtist, songTitle);

    char* artist = curl_easy_escape(_handle, songArtist.c_str(), 0);
    char* title = curl_easy_escape(_handle, songTitle.c_str(), 0);
    char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0);

    std::ostringstream query, sig;
    query << "method=track.updateNowPlaying&track=" << title
    << "&artist=" << artist
    << "&duration=" << song.getDuration()
    << "&api_key=" << APIKEY
    << "&sk=" << _sessionid;
    if(album) {
    query << "&album=" << album;
    sig << "album" << song.getAlbum();
    }

    curl_free(artist);
    curl_free(title);
    curl_free(album);

    sig << "api_key" << APIKEY
        << "artist" << songArtist
        << "duration" << song.getDuration()
        << "methodtrack.updateNowPlaying"
        << "sk" << _sessionid
        << "track" << songTitle
        << SECRET;

    std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

    query << "&api_sig=" << sighash;

    OpenURL(GetServiceURL(), query.str().c_str());

    if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
    iprintf("%s", "Updated \"Now Playing\" status successfully.");
    retval = true;
    }
    else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
    eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str());
    if(CheckFailure(_response))
        Failure();
    }

    CLEANUP();
    return retval;
}

void CAudioScrobbler::Handshake()
{
    std::string username="";
    for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {
    username.append(1, tolower(Config->getLUsername().c_str()[i]));
    }
    std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str()));

    std::ostringstream query, sig;
    query << "method=auth.getMobileSession&username=" << username << "&password=" << Config->getLPassword().c_str() << "&api_key=" << APIKEY;

    sig << "api_key" << APIKEY << "methodauth.getMobileSession" << "password" << Config->getLPassword().c_str() << "username" << username << SECRET;
    std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

    query << "&api_sig=" << sighash;

    OpenURL(GetServiceURL(), query.str().c_str());

    if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
    size_t start, end;
    start = _response.find("<key>") + 5;
    end = _response.find("</key>");
    _sessionid = _response.substr(start, end-start);
    iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str());
    _authed = true;
    }
    else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
    CheckFailure(_response);
    exit(EXIT_FAILURE);
    }

    CLEANUP();
}


text:
		<form action="testform.html" method="post">
			Email
			<input type="text" name="email" id="email" />
			Username
			<input type="text" name="username" id="username" />
			Password
			<input type="password" name="password" id="password" />
			<button type="submit" value="submit">Submit</button>
		</form>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.pirk.querier.wideskies</title>
<meta name="date" content="2016-10-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.pirk.querier.wideskies

Classes

EncryptionPropertiesBuilder

Querier

QuerierCLI

QuerierConst

QuerierDriver

QuerierFactory

QuerierProps


text:
using System;

namespace Shared.Core.Context
{
    /// <summary>
    /// Interface for Unit of Work with database. During the transaction all CRUD services or DAOs should share the same Unit of work.
    /// </summary>
    public interface IUnitOfWork : IDisposable
    {
        /// <summary>
        /// Gets the Context.
        /// </summary>
        /// <returns>The Database Context</returns>
        IDatabaseContext GetContext();

        /// <summary>
        /// Starts the transaction.
        /// </summary>
        void StartTransaction();

        /// <summary>
        /// Ends the transaction.
        /// </summary>
        void EndTransaction();
    }
}


text:
package Algorithms.Strings;

import java.util.Scanner;

/**
 * Created by ryu on 20/6/17.
 */
public class CamelCase {
    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        in.close();
        int count = 1;
        for (int i=0;i<s.length();i++) {
            if (Character.isUpperCase(s.charAt(i)))
                count++;
        }
        System.out.println(count);
    }
}


text:
package com.cuitrip.app.conversation;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by baziii on 15/8/7.
 */
public class ConversationAdapter extends RecyclerView.Adapter<ConversationsViewHolder> {
    List<ConversationItem> datas;

    public ConversationAdapter(ConversationsPresent present) {
        this.present = present;
    }

    ConversationsPresent present;

    public void setDatas(List<ConversationItem> datas) {
        this.datas = datas;
    }

    public void append(List<ConversationItem> datas) {
        if (this.datas == null) {
            this.datas = datas;
        } else {
            this.datas.addAll(datas);
        }
    }

    @Override
    public ConversationsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(ConversationsViewHolder.RES, parent, false);
        ConversationsViewHolder viewHolder = new ConversationsViewHolder(view, present);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ConversationsViewHolder holder, int position) {
        holder.render(datas.get(position));

    }

    @Override
    public int getItemCount() {
        return datas == null ? 0 : datas.size();
    }
}


text:
IF EXISTS (SELECT 1 FROM sys.procedures WHERE schema_id = SCHEMA_ID(N'Tigra') AND name = N'SelectRequirement')
BEGIN
	DROP PROCEDURE [Tigra].[SelectRequirement];
END
GO

CREATE PROCEDURE [Tigra].[SelectRequirement]
(
	@Cell VARCHAR(50),
	@LeftTag VARCHAR(100),
	@RightTag VARCHAR(100),
	@UserID INT,
	@Message VARCHAR(250)
)
AS
BEGIN

	BEGIN TRANSACTION;

	DECLARE @CellID INT, @LeftRevisionID BIGINT, @RightRevisionID BIGINT, @NewRightID BIGINT;

	SELECT @CellID = [CellID] FROM [Tigra].[Cells] WHERE [Tag] = @Cell;
	SELECT @LeftRevisionID = MAX([RevisionID]) FROM [Tigra].[RequirementRevisions] WHERE [Tag] = @LeftTag;
	SELECT @RightRevisionID = MAX([RevisionID]) FROM [Tigra].[RequirementRevisions] WHERE [Tag] = @RightTag;

	/* Cria a nova revisão. */
	INSERT INTO [Tigra].[RequirementRevisions] ([RequirementID], [RevisionNumber], [RevisionDate], [UserID], [Message], [Tag], [Title])
	SELECT [RequirementID], ([RevisionNumber] + 1), SYSUTCDATETIME(), @UserID, @Message, [Tag], [Title]
	FROM [Tigra].[RequirementRevisions]
	WHERE [RevisionID] = @RightRevisionID;

	SELECT @NewRightID = MAX([RevisionID]) FROM [Tigra].[RequirementRevisions] WHERE [Tag] = @RightTag;

	/* Copia o texto. */
	INSERT INTO [Tigra].[RequirementTexts] ([RevisionID], [Text])
	SELECT @NewRightID, [Text] FROM [Tigra].[RequirementTexts] WHERE [RevisionID] = @RightRevisionID;

	/* Cria o relacionamento. */
	INSERT INTO [Tigra].[RequirementRelations] ([LeftRevisionID], [RightRevisionID])
	VALUES (@LeftRevisionID, @NewRightID);

	COMMIT TRANSACTION;

END
GO


text:
<?php

namespace Mixpanel\Request;

/**
 * Curl CLI request method
 *
 * @author Espen Hovlandsdal <espen@hovlandsdal.com>
 * @copyright Copyright (c) 2013, Espen Hovlandsdal
 * @license http://www.opensource.org/licenses/mit-license MIT License
 * @link https://github.com/rexxars/mixpanel-php
 */
class CliCurl implements RequestInterface {

    /**
     * {@inheritdoc}
     */
    public function isSupported() {
        exec('curl --version >/dev/null 2>&1', $out, $error);
        return $error <= 2;
    }

    /**
     * {@inheritdoc}
     */
    public function request($url, $returnResponse = false) {
        $add = $returnResponse ? '' : ' >/dev/null 2>&1 &';
        $cmd = 'curl --silent ' . escapeshellarg($url) . $add;

        exec($cmd, $out, $error);

        return $returnResponse ? join(PHP_EOL, $out) : !$error;
    }

}


text:
Toy Resources
=========

Toy Resources is a component of [Toy Locomotive](https://github.com/Mortaro/Toy-Locomotive]), but can be used independently outside Toy Locomotive.

Getting Started
---------------

All you need to start using Toy Resources is to add the following lines to the respective files:

    # Gemfile
    gem "toy-resources"

    # config/routes.rb inside the 'draw block'
    toy_resources


text:
package org.apache.shiro.samples.sprhib.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.samples.sprhib.dao.UserDAO;
import org.apache.shiro.samples.sprhib.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Default implementation of the {@link UserService} interface.  This service implements
 * operations related to User data.
 */
@Transactional
@Service("userService")
public class DefaultUserService implements UserService {

    private UserDAO userDAO;

    @Autowired
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public User getCurrentUser() {
        final Long currentUserId = (Long) SecurityUtils.getSubject().getPrincipal();
        if( currentUserId != null ) {
            return getUser(currentUserId);
        } else {
            return null;
        }
    }

    public void createUser(String username, String email, String password) {
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword( new Sha256Hash(password).toHex() );
        userDAO.createUser( user );
    }

    public List<User> getAllUsers() {
        return userDAO.getAllUsers();
    }

    public User getUser(Long userId) {
        return userDAO.getUser(userId);
    }

    public void deleteUser(Long userId) {
        userDAO.deleteUser( userId );
    }

    public void updateUser(User user) {
        userDAO.updateUser( user );
    }

}


text:
Rainman is an experiment in writing drivers and handlers. It is a Ruby
implementation of the [abstract factory pattern][1]. Abstract factories provide
the general API used to interact with any number of interfaces. Interfaces
perform actual operations. Rainman provides a simple DSL for implementing this
design.

[1]: http://en.wikipedia.org/wiki/Abstract_factory_pattern

[Build Icon]: https://secure.travis-ci.org/site5/rainman.png?branch=master
[Build Status]: http://travis-ci.org/site5/rainman

## Drivers & Handlers

In Rainman, drivers represent abstract factories and handlers represent the
interfaces those factories interact with. In simpler terms, drivers define
_what_ things you can do; handlers define _how_ to do those things.

## Creating a driver

Rainman drivers are implemented as Modules. They must be extended with
`Rainman::Driver` and use the driver DSL to define their public API. An
example Domain driver might look like this:

```ruby
require 'rainman'

# The Domain module handles creating and deleting domains, and listing
# nameservers
module Domain
  extend Rainman::Driver

  # Register Domain::Abc as a handler.
  register_handler :abc

  # Register Domain::Xyz as a handler.
  register_handler :xyz

  # Register Domain.create as a public method
  define_action :create

  # Register Domain.destroy as a public method; Alias Domain.delete to it
  define_action :destroy, :alias => :delete

  # Register Domain.cancel as a public method; it delegates to a handler's
  # :cancel_account method.
  define_action :cancel, :delegate_to => :cancel_account

  # Register Domain.namservers.list as a public method
  namespace :nameservers do
    define_action :list
  end
end
```

## Implementing handlers

Driver handlers are implemented as classes. They must be within the namespace
of the driver Module. Using the example above, here are example handlers for
Abc and Xyz:

```ruby
class Domain::Abc
  # Public: Creates a new domain.
  #
  # Returns a Hash.
  def create(params = {})
  end

  # Public: Destroy a domain
  #
  # Returns true or false.
  def destroy(params = {})
  end

  # Public: Cancel a domain account
  #
  # Returns true or false.
  def cancel_account(params = {})
  end
end

class Domain::Xyz
  # Public: Creates a new domain.
  #
  # Returns a Hash.
  def create(params = {})
  end

  # Public: Destroy a domain
  #
  # Returns true or false.
  def destroy(params = {})
  end

  # Public: Cancel a domain account
  #
  # Returns true or false.
  def cancel_account(params = {})
  end
end
```

The example driver above also defined `nameservers` namespace with a `list`
action (eg: `Domain.nameservers.list`). To implement this, a Nameservers class
is created within each handler's namespace:

```ruby
class Domain::Abc::Nameserver

  # Public: Lists nameservers for this domain.
  #
  # Returns an Array.
  def list(params = {})
  end
end

class Domain::Xyz::Nameserver

  # Public: Lists nameservers for this domain.
  #
  # Returns an Array.
  def list(params = {})
  end
end
```

## Handler setup
If your handler requires any sort of setup that can't be handled in your
initialize method (e.g. you're subclassing and can't override
initialize), you can define a setup_handler method. Rainman will
automatically call this method for you after the class is initialized.

```ruby
class Domain::Abc
  attr_accessor :config

  def initialized
    @config = { :username => 'username', :password => 'password' }
  end
end

class Domain::Xyz < Domain::Abc
  def setup_handler
    @config[:username] = 'other'
  end
end
```

## Using a driver

With a driver and handler defined, the driver can now be used in a few
different ways.

### General

A driver's actions are available as singleton methods. By default, actions are
sent to the current handler, or a default handler if a handler is not currently
in use.

```ruby
# Create a domain
Domain.create({})

# Destroy a domain
Domain.destroy({})
Domain.delete({})

# Cancel domain acconut
Domain.cancel

# List domain nameservers
Domain.nameservers.list({})
```

### Changing handlers

It is possible to change the handler used at runtime using the `with_handler`
method. This method temporarily changes the current handler. This means, if
you have a default handler set, and use `with_handler`, that default handler
is preserved.

```ruby
Domain.with_handler(:abc) do |driver|
  # Here, current_handler is now set to :abc
  driver.create
end
```

You can also change the current handler for the duration of your code/session.

```ruby
Domain.set_current_handler :xyz
Domain.create # create an :xyz domain

Domain.set_current_handler :abc
Domain.create   # create an :abc domain
Domain.transfer # transfer an :abc domain
```

It is highly suggested you stick to using `with_handler` unless you have a
reason.

Convenience predicate methods are added for each handler to determine if it is
in use:

```ruby
Domain.abc?
Domain.xyz?
```

### Including drivers in other classes

A driver can be included in another class and its actions are available as
instance methods.

```ruby
class Service
  include Domain
end

s = Service.new

s.create

s.destroy
s.delete

s.cancel

s.nameservers.list

s.with_handler(:abc) do |handler|
  handler.create
end

s.set_current_handler :xyz
s.create
```

If you want to namespace a driver in another class, it's as easy as:

```ruby
class Service
  def domain
    Domain
  end
end

s = Service.new

s.domain.create

s.domain.destroy
s.domain.delete

s.domain.cancel

s.domain.nameservers.list

s.domain.with_handler(:abc) do |handler|
  handler.create
end

s.domain.set_current_handler :xyz
```

## Note on Patches/Pull Requests

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version
  unintentionally.
* Commit, do not bump version. (If you want to have your own version, that is
  fine but bump version in a commit by itself I can ignore when I pull).
* Send me a pull request. Bonus points for topic branches.

## Contributors

* [Justin Mazzi](https://github.com/jmazzi)
* [Joshua Priddle](https://github.com/itspriddle)

## Copyright

Copyright (c) 2012 Site5.com. See LICENSE for details.


text:
/* @flow */

/**
 * Given a string with a pattern that might infer access level, like `^_`,
 * create an inference method.
 *
 * @param {?string} pattern regexp-compatible pattern
 * @returns {Function} inference method
 * @private
 */
function inferAccessWithPattern(pattern: ?string) {
  var re = pattern && new RegExp(pattern);

  /**
   * Infers access (only private atm) from the name.
   *
   * @name inferAccess
   * @param {Object} comment parsed comment
   * @returns {Object} comment with access inferred
   */
  return function inferAccess(comment: Comment) {
    // This needs to run after inferName beacuse we infer the access based on
    // the name.
    if (
      re &&
      comment.name &&
      comment.access === undefined &&
      re.test(comment.name)
    ) {
      comment.access = 'private';
    }

    return comment;
  };
}

module.exports = inferAccessWithPattern;


text:
<title>Insert Details</title>

<form name="form1" action="insert.php" method="POST">

First Name:
<input type="text" name="first_name" placeholder="Enter First Name"/>

Last Name:
<input type="text" name="last_name" placeholder="Enter Last Name"/>

Age
<input type="text" name="age" placeholder="Enter AGE"/>

City
<input type="text" name="city" placeholder="Enter City"/>

<input type="submit" name="submit">

</form>


text:
// Code generated by protoc-gen-go.
// source: message.proto
// DO NOT EDIT!

/*
Package message is a generated protocol buffer package.

It is generated from these files:
	message.proto

It has these top-level messages:
	Note
*/
package message

import proto "github.com/golang/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

type Note struct {
	Name             *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"`
	Date             *int64  `protobuf:"varint,2,req,name=date" json:"date,omitempty"`
	Comment          *string `protobuf:"bytes,3,req,name=comment" json:"comment,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *Note) Reset()         { *m = Note{} }
func (m *Note) String() string { return proto.CompactTextString(m) }
func (*Note) ProtoMessage()    {}

func (m *Note) GetName() string {
	if m != nil && m.Name != nil {
		return *m.Name
	}
	return ""
}

func (m *Note) GetDate() int64 {
	if m != nil && m.Date != nil {
		return *m.Date
	}
	return 0
}

func (m *Note) GetComment() string {
	if m != nil && m.Comment != nil {
		return *m.Comment
	}
	return ""
}

func init() {
}


text:
from django.core.management.base import BaseCommand
from ... import tools

class Command(BaseCommand):
    help = 'Stop Call List'

    def add_arguments(self, parser):
        parser.add_argument('--id', dest='call_list_id', type=int)

    def handle(self, *args, **options):
        call_list_id = options['call_list_id']
        tools.call_list_stop(call_list_id)


text:
<?php
# Utilisateur MySQL
define('DB_USER','manoloexpo');

# Mot de passe MySQL
define('DB_PASS','**********');

# Nom de machine MySQL (généralement localhost)
define('DB_HOST','sql.free.fr');

# Nom de la base de données
define('DB_DBASE','manoloexpo');

# Clé de session
define('GJ_SESSION','*********');

# Mot de passe de session
define('GJ_PWD_SESSION','*********');
?>


text:
package org.locationtech.geomesa.fs.data

import com.typesafe.scalalogging.LazyLogging
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileContext, Path}
import org.geotools.data.Query
import org.geotools.data.store.{ContentDataStore, ContentEntry, ContentFeatureSource}
import org.locationtech.geomesa.fs.storage.api._
import org.locationtech.geomesa.fs.storage.common.StorageKeys
import org.locationtech.geomesa.fs.storage.common.metadata.FileBasedMetadata
import org.locationtech.geomesa.index.stats.RunnableStats.UnoptimizedRunnableStats
import org.locationtech.geomesa.index.stats.{GeoMesaStats, HasGeoMesaStats}
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.locationtech.geomesa.utils.index.GeoMesaSchemaValidator
import org.locationtech.geomesa.utils.io.CloseQuietly
import org.opengis.feature.`type`.Name
import org.opengis.feature.simple.SimpleFeatureType

import scala.concurrent.duration.Duration
import scala.util.control.NonFatal

class FileSystemDataStore(
    fc: FileContext,
    conf: Configuration,
    root: Path,
    readThreads: Int,
    writeTimeout: Duration,
    defaultEncoding: Option[String],
    namespace: Option[String]
  ) extends ContentDataStore with HasGeoMesaStats with LazyLogging {

  namespace.foreach(setNamespaceURI)

  private val manager = FileSystemStorageManager(fc, conf, root, namespace)

  override val stats: GeoMesaStats = new UnoptimizedRunnableStats(this)

  override def createTypeNames(): java.util.List[Name] = {
    val names = new java.util.ArrayList[Name]()
    manager.storages().foreach(storage => names.add(storage.metadata.sft.getName))
    names
  }

  override def createSchema(original: SimpleFeatureType): Unit = {
    import org.locationtech.geomesa.fs.storage.common.RichSimpleFeatureType

    manager.storage(original.getTypeName) match {
      case Some(s) =>
        logger.warn(s"Schema already exists: ${SimpleFeatureTypes.encodeType(s.metadata.sft, includeUserData = true)}")

      case None =>
        // copy the feature type so that we don't affect it when removing user data, below
        val sft = SimpleFeatureTypes.copy(original)

        GeoMesaSchemaValidator.validate(sft)

        // remove the configs in the user data as they're persisted separately
        val meta = sft.removeMetadata().getOrElse(FileBasedMetadata.DefaultOptions)
        val scheme = sft.removeScheme().getOrElse {
          throw new IllegalArgumentException("Partition scheme must be specified in the SimpleFeatureType user data")
        }
        val encoding = sft.removeEncoding().orElse(defaultEncoding).getOrElse {
          throw new IllegalArgumentException("Encoding type must be specified in either " +
              "the SimpleFeatureType user data or the data store parameters")
        }
        val leafStorage = sft.removeLeafStorage().getOrElse {
          val deprecated = scheme.options.get("leaf-storage").map { s =>
            logger.warn("Using deprecated leaf-storage partition-scheme option. Please define leaf-storage using " +
                s"""`simpleFeatureType.getUserData.put("${StorageKeys.LeafStorageKey}", "$s")`""")
            s.toBoolean
          }
          deprecated.getOrElse(true)
        }
        val fileSize = sft.removeTargetFileSize()

        val path = manager.defaultPath(sft.getTypeName)
        val context = FileSystemContext(fc, conf, path, namespace)

        val metadata =
          StorageMetadataFactory.create(context, meta, Metadata(sft, encoding, scheme, leafStorage, fileSize))
        try { manager.register(path, FileSystemStorageFactory(context, metadata)) } catch {
          case NonFatal(e) => CloseQuietly(metadata).foreach(e.addSuppressed); throw e
        }
    }
  }

  override def createFeatureSource(entry: ContentEntry): ContentFeatureSource =
    new FileSystemFeatureStore(storage(entry.getTypeName), entry, Query.ALL, readThreads, writeTimeout)

  /**
    * Get a handle on the underlying storage instance for a given simple feature type
    *
    * @param typeName simple feature type name
    * @return
    */
  def storage(typeName: String): FileSystemStorage = manager.storage(typeName).getOrElse {
    throw new IllegalArgumentException(s"Schema '$typeName' doesn't exist or could not be loaded")
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlueYonder.BookingService.Host
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        // TODO: Module 5: Exercise 2: Task 2.1: Implement the IBookingService interface
    }
}


text:
<?php

/**
 * Podium Module
 * Yii 2 Forum Module
 */
namespace bizley\podium\models;

use bizley\podium\components\Helper;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;

/**
 * Meta model
 * User's meta data.
 *
 * @author Paweł Bizley Brzozowski <pb@human-device.com>
 * @since 0.1
 * @property integer $id
 * @property integer $user_id
 * @property string $location
 * @property string $signature
 * @property integer $gravatar
 * @property string $avatar
 * @property integer $created_at
 * @property integer $updated_at
 */
class Meta extends ActiveRecord
{

    const MAX_WIDTH  = 165;
    const MAX_HEIGHT = 165;
    const MAX_SIZE   = 204800;

    /**
     * @var mixed Avatar image
     */
    public $image;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%podium_user_meta}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [TimestampBehavior::className()];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['location', 'signature'], 'trim'],
            ['location', 'filter', 'filter' => function($value) {
                return HtmlPurifier::process(Html::encode($value));
            }],
            ['gravatar', 'boolean'],
            ['image', 'image', 'mimeTypes' => 'image/png, image/jpeg, image/gif', 'maxWidth' => self::MAX_WIDTH, 'maxHeight' => self::MAX_HEIGHT, 'maxSize' => self::MAX_SIZE],
            ['signature', 'filter', 'filter' => function($value) {
                return HtmlPurifier::process($value, Helper::podiumPurifierConfig('minimal'));
            }],
            ['signature', 'string', 'max' => 512],
        ];
    }
}


text:
#include "gui/LayoutAlgorithm.h"

#include <algorithm>

#include "gui/Widget.h"

LayoutProperties LayoutAlgorithm::CalculateLayoutPropertiesRelative(
	const std::vector<std::shared_ptr<Widget>>& children,
	const LayoutProperties layoutProps,
	const DisplayProperties displayProps)
{
	LayoutProperties newLayoutProps = layoutProps;

	auto desiredPixelSize = layoutProps.DesiredPixelSize(displayProps.m_dpi);
	float maxDesiredW = desiredPixelSize.x;
	float maxDesiredH = desiredPixelSize.y;

	for (auto child : children)
	{
		if (child->IsVisible())
		{
			auto& childLayoutProps = child->GetLayoutPropertiesConstRef();
			auto childDesiredPixelSize = childLayoutProps.m_desiredPixelSize;
			maxDesiredW = std::max(maxDesiredW, childDesiredPixelSize.x);
			maxDesiredH = std::max(maxDesiredH, childDesiredPixelSize.y);
		}
	}

	newLayoutProps.m_childGrowHorizontally = false;
	newLayoutProps.m_childGrowVertically = false;
	newLayoutProps.m_desiredPixelSize = Vec2f(maxDesiredW, maxDesiredH);
	return newLayoutProps;
}

void LayoutAlgorithm::CalculateChildrenPlacementsRelative(
	const std::vector<std::shared_ptr<Widget>>& children,
	const Vec2f position,
	const Vec2f size,
	const Vec2f depthRange,
	std::unordered_map<UUID, WidgetPlacement>& childrenPlacements)
{
	const float childDepthRangeSize =
		(depthRange.x - depthRange.y) / (children.size() + 1);
	float childDepthRangeStart = depthRange.x - childDepthRangeSize;

	auto zSortedChildren = children;

	std::sort(zSortedChildren.begin(), zSortedChildren.end(),
	[](const std::shared_ptr<Widget>& a, const std::shared_ptr<Widget>& b)
	{
		return a->GetLayoutPropertiesConstRef().m_z
			< b->GetLayoutPropertiesConstRef().m_z;
	});

	for (auto child : zSortedChildren)
	{
		WidgetPlacement childPlacement;

		if (child->IsVisible())
		{
			auto& childLayoutProps = child->GetLayoutPropertiesConstRef();

			Vec2f childSize = childLayoutProps.m_relSize * size;

			if (!childLayoutProps.m_desiredSize.AnyEquals(0.0f))
			{
				if (childLayoutProps.m_desiredPixelSize.x < childSize.x
					&& childLayoutProps.m_desiredPixelSize.y < childSize.y)
				{
					childSize = childLayoutProps.m_desiredPixelSize;
				}
			}

			childPlacement.m_position =
				position + childLayoutProps.m_relPosition * size;
			childPlacement.m_size = childSize;
		}

		float maxDepth = childDepthRangeStart;
		float minDepth = childDepthRangeStart - childDepthRangeSize;

		childPlacement.m_depthRange = Vec2f(maxDepth, minDepth);
		childPlacement.m_depth = maxDepth;
		childrenPlacements.insert(
			std::make_pair(child->GetId(), childPlacement));

		childDepthRangeStart -= childDepthRangeSize;
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="brain_shim_rat_9_4T_01" author="Agilent" investigator=""
  ExpSelNoShow="true" application="imaging" rfcoil="72mm_4ch" anatomy="head" species="rat" time_created="20130603T120829"
  parfile="brain_shim_rat_9_4T_01" apptype="im2Dfse" label="" scans="brain_shim_rat_9_4T_01" seqfil="ge3dshim">
  <protocol title="brain_shim_rat_9_4T_01" type="protocol">
    <action   type="LIB" status="Ready" title="brain_shim_rat_9_4T" exp="brain_shim_rat_9_4T" lock="off" time="5.1s" data="" macro="sqexp('studycard','Head_Basic_Anatomy_rat_9_4T','brain_shim_rat_9_4T_01')" />
  </protocol>
</template>


text:
package de.jtem.blas;

import javax.swing.table.AbstractTableModel;

abstract class AbstractMatrixTableModel extends AbstractTableModel {

    AbstractMatrix matrix;

    public String getColumnName(int column)
    {
	return String.valueOf(column);
    }
    public int findColumn(String columnName)
    {
	return Integer.parseInt(columnName);
    }
    public Class getColumnClass(int columnIndex)
    {
	return String.class;
    }
    public int getRowCount()
    {
	return matrix.getNumRows();
    }
    public int getColumnCount()
    {
	return matrix.getNumCols();
    }
    public boolean isCellEditable(int rowIndex, int columnIndex)
    {
	return true;
    }
    public void setMatrix(AbstractMatrix mat)
    {
	matrix=mat;
	fireTableStructureChanged();
    }
    public AbstractMatrix getMatrix()
    {
	return matrix;
    }
}


text:
exports.default = function(req, res) {
    res.render('press/default');
};


text:
`Mongoid::Paranoia` enables a "soft delete" of Mongoid documents. Instead of being removed from the database, paranoid docs are flagged with a `deleted_at` timestamp and are ignored from queries by default.

The `Mongoid::Paranoia` functionality was originally supported in Mongoid itself, but was dropped from version 4.0.0 onwards. This gem was extracted from the [Mongoid 3.0.0-stable branch](https://github.com/mongoid/mongoid/tree/3.0.0-stable). This gem should not be used with Mongoid versions 3.x and prior. Current master branch targeted on Mongoid 6.0. With release 0.3.0 Mongoid 4 and 5 versions will be dropped.

**Caution:** This repo/gem `mongoid_paranoia` (underscored) is different than [mongoid-paranoia](https://github.com/haihappen/mongoid-paranoia) (hyphenated). The goal of `mongoid-paranoia` (hyphenated) is to stay API compatible and it only accepts security fixes.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'mongoid_paranoia'
```

## Usage

```ruby
class Person
  include Mongoid::Document
  include Mongoid::Paranoia
end

person.delete   # Sets the deleted_at field to the current time, ignoring callbacks.
person.delete!  # Permanently deletes the document, ignoring callbacks.
person.destroy  # Sets the deleted_at field to the current time, firing callbacks.
person.destroy! # Permanently deletes the document, firing callbacks.
person.restore  # Brings the "deleted" document back to life.
person.restore(:recursive => true) # Brings "deleted" associated documents back to life recursively
```

The documents that have been "flagged" as deleted (soft deleted) can be accessed at any time by calling the deleted class method on the class.

```ruby
Person.deleted # Returns documents that have been "flagged" as deleted.
```

You can also access all documents (both deleted and non-deleted) at any time by using the `unscoped` class method:

```ruby
Person.unscoped.all # Returns all documents, both deleted and non-deleted
```

You can also configure the paranoid field naming on a global basis.  Within the context of a Rails app this is done via an initializer.

```ruby
# config/initializers/mongoid_paranoid.rb

Mongoid::Paranoia.configure do |c|
  c.paranoid_field = :myFieldName
end
```

### Validations
#### You need override uniqueness validates

```ruby
validates :title, uniqueness: { conditions: -> { where(deleted_at: nil) } }
```

### Callbacks

#### Restore
`before_restore`, `after_restore` and `around_restore` callbacks are added to your model. They work similarly to the `before_destroy`, `after_destroy` and `around_destroy` callbacks.

#### Remove
`before_remove`, `after_remove` and `around_remove` are added to your model. They are called when record is deleted permanently .

#### Example
```ruby
class User
  include Mongoid::Document
  include Mongoid::Paranoia

  before_restore :before_restore_action
  after_restore  :after_restore_action
  around_restore :around_restore_action

  private

  def before_restore_action
    puts "BEFORE"
  end

  def after_restore_action
    puts "AFTER"
  end

  def around_restore_action
    puts "AROUND - BEFORE"
    yield # restoring
    puts "AROUND - AFTER"
  end
end
```

## TODO
- get rid of [monkey_patches.rb](https://github.com/simi/mongoid_paranoia/blob/master/lib/mongoid/paranoia/monkey_patches.rb)
- [review persisted? behaviour](https://github.com/simi/mongoid_paranoia/issues/2)

## Authors

* original [Mongoid](https://github.com/mongoid/mongoid) implementation by [@durran](https://github.com/durran)
* extracted from [Mongoid](https://github.com/mongoid/mongoid) by [@simi](https://github.com/simi)
* [documentation improvements](https://github.com/simi/mongoid_paranoia/pull/3) by awesome [@loopj](https://github.com/loopj)
* [latest mongoid support, restore_callback support](https://github.com/simi/mongoid_paranoia/pull/8) by fabulous [@zhouguangming](https://github.com/zhouguangming)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
define([
	'backbone',

	'app/collection/currentlywatching',
	'app/view/panel/currentlywatching/item',
	'app/func/intervaltimeout',

	'bootstrap'
], function(Backbone, Collection, ItemView, Timeout) {

	var View = Backbone.View.extend({
		el: '.currently-watching',

		slideCounter: 0,

		initialize: function() {
			this.collection = new Collection();
			this.collection.on('add', this.addPoster, this);
			this.collection.on('remove', this.removePoster, this);

			this.timeout = Timeout(this.fetch.bind(this), Config.UpdateDelay);
			this.timeout.start();

		},

		fetch: function() {
			this.collection.fetch();
		},

		addPoster: function(poster) {
			this.slideCounter += 1;

			poster.view = new ItemView({ model: poster }, this.$('.carousel'));
			poster.view.resizeImg();

			var view = poster.view.render().addClass((this.slideCounter == 1) ? ' active' : '');
			this.$('.carousel-inner').append(view);

			this.startSlideshow();
		},

		startSlideshow: function() {
			this.$('.currentlyWactchingNothing').fadeOut();
			this.resetCarousel();
		},

		removePoster: function(video) {
			video.view.removePoster();

			this.slideCounter -= 1;
			if(this.slideCounter == 0) {
				this.$('.currentlyWactchingNothing').fadeIn();
			} else {
				this.resetCarousel();
			}
		},

		resetCarousel: function() {
			var $carousel = this.$('.carousel')
			  , data = $carousel.data('bs.carousel');

			if(data) {
				var $items = $carousel.find('.item');
				$items.removeClass('active next left right last');
				$($items[0]).addClass('active');

				data.$element.off('.' + data.type).removeData('bs.' + data.type);
				$carousel.data('bs.carousel', false);
			}
			$carousel.carousel();
		}
	});

	return View;
});


text:
package org.jitsi.impl.androidupdate;

import net.java.sip.communicator.service.update.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.osgi.framework.*;

/**
 * Android update service activator.
 *
 * @author Pawel Domas
 */
public class UpdateActivator
    extends SimpleServiceActivator<UpdateService>
{
    /**
     * <tt>BundleContext</tt> instance.
     */
    static BundleContext bundleContext;

    /**
     * Creates new instance of <tt>UpdateActivator</tt>.
     */
    public UpdateActivator()
    {
        super(UpdateService.class, "Android update service");
    }

    /**
     * Gets the <tt>ConfigurationService</tt> using current
     * <tt>BundleContext</tt>.
     * @return the <tt>ConfigurationService</tt>
     */
    public static ConfigurationService getConfiguration()
    {
        return ServiceUtils.getService(
            bundleContext, ConfigurationService.class);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected UpdateService createServiceImpl()
    {
        return new UpdateServiceImpl();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start(BundleContext bundleContext) throws Exception
    {
        UpdateActivator.bundleContext = bundleContext;

        super.start(bundleContext);

        ((UpdateServiceImpl)serviceImpl).removeOldDownloads();
    }
}


text:
//
//  DMLDataManager.m
//  Locations
//
//  Created by dongmeiliang on 5/23/14.
//  Copyright (c) 2014 dongmeilianghy@sina.com. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>

#import "DMLDataManager.h"

#import "DMLLocationsStack.h"
#import "Event.h"

@interface DMLDataManager ()

@property (nonatomic, readwrite, strong) DMLLocationsStack *locationsStack;

@end

@implementation DMLDataManager

- (instancetype) init
{
    return nil;
}

+ (instancetype)sharedDataManager
{
    static DMLDataManager *sDataManager = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sDataManager = [[self alloc] initSingleton];
    });

    return sDataManager;
}

- (instancetype)initSingleton
{
    self = [super init];
    if (self) {
        self.locationsStack = [[DMLLocationsStack alloc] initWithStoreURL:[self storeURL] modelURL:[self modelURL]];
    }

    return self;
}

- (NSMutableArray *)fetchEventDataFromPersistentStore
{
    /*
	 Fetch existing events.
	 Create a fetch request; find the Event entity and assign it to the request; add a sort descriptor; then execute the fetch.
	 */

	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.locationsStack.managedObjectContext];
	[request setEntity:entity];

	// Order the events by creation date, most recent first.
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
	[request setSortDescriptors:sortDescriptors];

	// Execute the fetch -- create a mutable copy of the result.
	NSError *error = nil;
	NSMutableArray *mutableFetchResults = [[self.locationsStack.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
	if (mutableFetchResults == nil) {
		// Handle the error.
	}

	 return mutableFetchResults;
}

- (Event *)createEventCoordinate:(CLLocationCoordinate2D)coordinate creationDate:(NSDate *)date error:(NSError **)err
{
    /*
	 Create a new instance of the Event entity.
	 */
	Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:self.locationsStack.managedObjectContext];

    //	// Configure the new event with information from the location.
    //	CLLocationCoordinate2D coordinate = [location coordinate];
	[event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]];
	[event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]];

	// Should be the location's timestamp, but this will be constant for simulator.
	// [event setCreationDate:[location timestamp]];
	[event setCreationDate:date];

	[self.locationsStack.managedObjectContext save:err];

    return event;
}

#pragma mark - Utilities

- (NSURL*)storeURL
{
    NSURL* documentsDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
    return [documentsDirectory URLByAppendingPathComponent:@"Locations.sqlite"];
}

- (NSURL*)modelURL
{
    return [[NSBundle mainBundle] URLForResource:@"Locations" withExtension:@"momd"];
}

@end


text:
'use strict';

/**
 * @ngdoc service
 * @name boatDatingApp.User
 * @description
 * # User
 * Service in the boatDatingApp.
 */
angular.module('core').service('User', ['Storage', function User(Storage) {
        return{
            /**
             * Return  the current user stored in local Storage
             *
             * @returns {{}}
             */
            get: function() {
                return Storage.get('auth_token') ? Storage.get('auth_token').user : {}
            }
        };
    }]);


text:
namespace crashpad {

// Ref:
// http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
void AppendCommandLineArgument(const std::wstring& argument,
                               std::wstring* command_line) {
  if (!command_line->empty()) {
    command_line->push_back(L' ');
  }

  // Don't bother quoting if unnecessary.
  if (!argument.empty() &&
      argument.find_first_of(L" \t\n\v\"") == std::wstring::npos) {
    command_line->append(argument);
  } else {
    command_line->push_back(L'"');
    for (std::wstring::const_iterator i = argument.begin();; ++i) {
      size_t backslash_count = 0;
      while (i != argument.end() && *i == L'\\') {
        ++i;
        ++backslash_count;
      }
      if (i == argument.end()) {
        // Escape all backslashes, but let the terminating double quotation mark
        // we add below be interpreted as a metacharacter.
        command_line->append(backslash_count * 2, L'\\');
        break;
      } else if (*i == L'"') {
        // Escape all backslashes and the following double quotation mark.
        command_line->append(backslash_count * 2 + 1, L'\\');
        command_line->push_back(*i);
      } else {
        // Backslashes aren't special here.
        command_line->append(backslash_count, L'\\');
        command_line->push_back(*i);
      }
    }
    command_line->push_back(L'"');
  }
}

}  // namespace crashpad


text:
/**
 * \file
 *         Rime buffer (packetbuf) management
 * \author
 *         Adam Dunkels <adam@sics.se>
 */

/**
 * \addtogroup packetbuf
 * @{
 */

#include <string.h>

#include "contiki-net.h"
#include "net/packetbuf.h"
#include "net/rime/rime.h"
#include "sys/cc.h"

struct packetbuf_attr packetbuf_attrs[PACKETBUF_NUM_ATTRS];
struct packetbuf_addr packetbuf_addrs[PACKETBUF_NUM_ADDRS];

static uint16_t buflen, bufptr;
static uint8_t hdrlen;

/* The declarations below ensure that the packet buffer is aligned on
   an even 32-bit boundary. On some platforms (most notably the
   msp430 or OpenRISC), having a potentially misaligned packet buffer may lead to
   problems when accessing words. */
static uint32_t packetbuf_aligned[(PACKETBUF_SIZE + 3) / 4];
static uint8_t *packetbuf = (uint8_t *)packetbuf_aligned;

#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif

/*---------------------------------------------------------------------------*/
void
packetbuf_clear(void)
{
  buflen = bufptr = 0;
  hdrlen = 0;

  packetbuf_attr_clear();
}
/*---------------------------------------------------------------------------*/
int
packetbuf_copyfrom(const void *from, uint16_t len)
{
  uint16_t l;

  packetbuf_clear();
  l = MIN(PACKETBUF_SIZE, len);
  memcpy(packetbuf, from, l);
  buflen = l;
  return l;
}
/*---------------------------------------------------------------------------*/
void
packetbuf_compact(void)
{
  int16_t i;

  if(bufptr) {
    /* shift data to the left */
    for(i = 0; i < buflen; i++) {
      packetbuf[hdrlen + i] = packetbuf[packetbuf_hdrlen() + i];
    }
    bufptr = 0;
  }
}
/*---------------------------------------------------------------------------*/
int
packetbuf_copyto(void *to)
{
  if(hdrlen + buflen > PACKETBUF_SIZE) {
    return 0;
  }
  memcpy(to, packetbuf_hdrptr(), hdrlen);
  memcpy((uint8_t *)to + hdrlen, packetbuf_dataptr(), buflen);
  return hdrlen + buflen;
}
/*---------------------------------------------------------------------------*/
int
packetbuf_hdralloc(int size)
{
  int16_t i;

  if(size + packetbuf_totlen() > PACKETBUF_SIZE) {
    return 0;
  }

  /* shift data to the right */
  for(i = packetbuf_totlen() - 1; i >= 0; i--) {
    packetbuf[i + size] = packetbuf[i];
  }
  hdrlen += size;
  return 1;
}
/*---------------------------------------------------------------------------*/
int
packetbuf_hdrreduce(int size)
{
  if(buflen < size) {
    return 0;
  }

  bufptr += size;
  buflen -= size;
  return 1;
}
/*---------------------------------------------------------------------------*/
void
packetbuf_set_datalen(uint16_t len)
{
  PRINTF("packetbuf_set_len: len %d\n", len);
  buflen = len;
}
/*---------------------------------------------------------------------------*/
void *
packetbuf_dataptr(void)
{
  return packetbuf + packetbuf_hdrlen();
}
/*---------------------------------------------------------------------------*/
void *
packetbuf_hdrptr(void)
{
  return packetbuf;
}
/*---------------------------------------------------------------------------*/
uint16_t
packetbuf_datalen(void)
{
  return buflen;
}
/*---------------------------------------------------------------------------*/
uint8_t
packetbuf_hdrlen(void)
{
  return bufptr + hdrlen;
}
/*---------------------------------------------------------------------------*/
uint16_t
packetbuf_totlen(void)
{
  return packetbuf_hdrlen() + packetbuf_datalen();
}
/*---------------------------------------------------------------------------*/
void
packetbuf_attr_clear(void)
{
  int i;
  memset(packetbuf_attrs, 0, sizeof(packetbuf_attrs));
  for(i = 0; i < PACKETBUF_NUM_ADDRS; ++i) {
    linkaddr_copy(&packetbuf_addrs[i].addr, &linkaddr_null);
  }
}
/*---------------------------------------------------------------------------*/
void
packetbuf_attr_copyto(struct packetbuf_attr *attrs,
		    struct packetbuf_addr *addrs)
{
  memcpy(attrs, packetbuf_attrs, sizeof(packetbuf_attrs));
  memcpy(addrs, packetbuf_addrs, sizeof(packetbuf_addrs));
}
/*---------------------------------------------------------------------------*/
void
packetbuf_attr_copyfrom(struct packetbuf_attr *attrs,
		      struct packetbuf_addr *addrs)
{
  memcpy(packetbuf_attrs, attrs, sizeof(packetbuf_attrs));
  memcpy(packetbuf_addrs, addrs, sizeof(packetbuf_addrs));
}
/*---------------------------------------------------------------------------*/
#if !PACKETBUF_CONF_ATTRS_INLINE
int
packetbuf_set_attr(uint8_t type, const packetbuf_attr_t val)
{
  packetbuf_attrs[type].val = val;
  return 1;
}
/*---------------------------------------------------------------------------*/
packetbuf_attr_t
packetbuf_attr(uint8_t type)
{
  return packetbuf_attrs[type].val;
}
/*---------------------------------------------------------------------------*/
int
packetbuf_set_addr(uint8_t type, const linkaddr_t *addr)
{
  linkaddr_copy(&packetbuf_addrs[type - PACKETBUF_ADDR_FIRST].addr, addr);
  return 1;
}
/*---------------------------------------------------------------------------*/
const linkaddr_t *
packetbuf_addr(uint8_t type)
{
  return &packetbuf_addrs[type - PACKETBUF_ADDR_FIRST].addr;
}
/*---------------------------------------------------------------------------*/
#endif /* PACKETBUF_CONF_ATTRS_INLINE */
int
packetbuf_holds_broadcast(void)
{
  return linkaddr_cmp(&packetbuf_addrs[PACKETBUF_ADDR_RECEIVER - PACKETBUF_ADDR_FIRST].addr, &linkaddr_null);
}
/*---------------------------------------------------------------------------*/

/** @} */