text:
import './middleware.any.js';

import { IStore } from '../../app/types';
import { showNotification } from '../../notifications/actions';
import { NOTIFICATION_TIMEOUT_TYPE } from '../../notifications/constants';
import LocalRecordingManager from '../../recording/components/Recording/LocalRecordingManager.web';
// eslint-disable-next-line lines-around-comment
// @ts-ignore
import StopRecordingDialog from '../../recording/components/Recording/web/StopRecordingDialog';
import { openDialog } from '../dialog/actions';
import MiddlewareRegistry from '../redux/MiddlewareRegistry';

import { SET_VIDEO_MUTED } from './actionTypes';

import './subscriber';

/**
 * Implements the entry point of the middleware of the feature base/media.
 *
 * @param {IStore} store - The redux store.
 * @returns {Function}
 */
MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: any) => {
    const { dispatch } = store;

    switch (action.type) {
    case SET_VIDEO_MUTED: {
        if (LocalRecordingManager.isRecordingLocally() && LocalRecordingManager.selfRecording.on) {
            if (action.muted && LocalRecordingManager.selfRecording.withVideo) {
                dispatch(openDialog(StopRecordingDialog, { localRecordingVideoStop: true }));

                return;
            } else if (!action.muted && !LocalRecordingManager.selfRecording.withVideo) {
                dispatch(showNotification({
                    titleKey: 'recording.localRecordingNoVideo',
                    descriptionKey: 'recording.localRecordingVideoWarning',
                    uid: 'recording.localRecordingNoVideo'
                }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));
            }
        }
    }
    }

    return next(action);
});

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.oauthclienttest;

import java.util.Map;
import org.json.simple.JSONValue;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.model.Token;

/**
 *
 * @author Roberto
 */
public class VSOTokenExtractor implements AccessTokenExtractor {

    private static final String EMPTY_SECRET = "";

    @Override
    public Token extract(String string) {

        Map json = (Map) JSONValue.parse(string);
        String token = (String) json.get("access_token");
        return new Token(token, EMPTY_SECRET);
    }
}


text:
struct MysqlResponse;
class MysqlCommandListener
{
public:
    MysqlCommandListener(){}
    virtual ~MysqlCommandListener(){}
public:
    virtual  int     OnResponse(MysqlResponse & rsp);
};
typedef shared_ptr<MysqlCommandListener>  MysqlCommandListenerPtr;
////////////////////////////////////////////////////////////


text:
package org.sfs.integration.java.func;

import com.google.common.collect.ListMultimap;
import com.google.common.escape.Escaper;
import com.google.common.net.MediaType;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.logging.Logger;
import org.sfs.rx.ObservableFuture;
import org.sfs.rx.RxHelper;
import rx.Observable;
import rx.functions.Func1;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Joiner.on;
import static com.google.common.collect.ArrayListMultimap.create;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.net.HttpHeaders.ACCEPT;
import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.UrlEscapers.urlFormParameterEscaper;
import static io.vertx.core.logging.LoggerFactory.getLogger;
import static java.util.Collections.addAll;
import static org.sfs.integration.java.help.AuthorizationFactory.Producer;

public class GetAccount implements Func1<Void, Observable<HttpClientResponse>> {

    private static final Logger LOGGER = getLogger(GetAccount.class);
    private final HttpClient httpClient;
    private final String accountName;
    private final Producer auth;
    private ListMultimap<String, String> queryParams = create();
    private ListMultimap<String, String> headerParams = create();

    public GetAccount(HttpClient httpClient, String accountName, Producer auth) {
        this.httpClient = httpClient;
        this.accountName = accountName;
        this.auth = auth;
    }

    public GetAccount setMediaTypes(List<MediaType> mediaTypes) {
        headerParams.removeAll(ACCEPT);
        headerParams.putAll(ACCEPT,
                from(mediaTypes)
                        .transform(input -> input.toString()));
        return this;
    }

    public GetAccount setMediaTypes(MediaType mediaType, MediaType... mediaTypes) {
        List<MediaType> types = new ArrayList<>(1 + mediaTypes.length);
        types.add(mediaType);
        addAll(types, mediaTypes);
        return setMediaTypes(types);
    }

    public GetAccount setHeader(String name, String value) {
        headerParams.removeAll(name);
        headerParams.put(name, value);
        return this;
    }

    public GetAccount setHeader(String name, String value, String... values) {
        headerParams.removeAll(name);
        headerParams.put(name, value);
        for (String v : values) {
            headerParams.put(name, v);
        }
        return this;
    }

    public GetAccount setQueryParam(String name, String value) {
        queryParams.removeAll(name);
        queryParams.put(name, value);
        return this;
    }

    public GetAccount setQueryParam(String name, String value, String... values) {
        queryParams.removeAll(name);
        queryParams.put(name, value);
        for (String v : values) {
            queryParams.put(name, v);
        }
        return this;
    }

    @Override
    public Observable<HttpClientResponse> call(Void aVoid) {
        return auth.toHttpAuthorization()
                .flatMap(new Func1<String, Observable<HttpClientResponse>>() {
                    @Override
                    public Observable<HttpClientResponse> call(String s) {

                        final Escaper escaper = urlFormParameterEscaper();

                        Iterable<String> keyValues = from(queryParams.entries())
                                .transform(input -> escaper.escape(input.getKey()) + '=' + escaper.escape(input.getValue()));

                        String query = on('&').join(keyValues);

                        ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                        HttpClientRequest httpClientRequest = httpClient.get("/openstackswift001/" + accountName + (query.length() > 0 ? "?" + query : ""), handler::complete)
                                .exceptionHandler(handler::fail)
                                .setTimeout(10000)
                                .putHeader(AUTHORIZATION, s);

                        for (String entry : headerParams.keySet()) {
                            httpClientRequest = httpClientRequest.putHeader(entry, headerParams.get(entry));
                        }
                        httpClientRequest.end();
                        return handler
                                .single();
                    }
                });

    }
}


text:
set -e

tempDir="../include/flatbuffers/.tmp"
originalFile="../include/flatbuffers/reflection_generated.h"
newFile="$tempDir/reflection_generated.h"

../flatc -c --cpp-std c++0x --no-prefix -o $tempDir reflection.fbs

if [ -f "$newFile" ]; then
  if ! cmp -s "$originalFile" "$newFile"; then
    mv $newFile $originalFile
  else
    rm $newFile
  fi
  rmdir $tempDir
fi


text:
Title: December updates
Date: 2021-12-14 00:00 CET
Tags: NumFOCUS,Updates
slug: december-updates
lang: en
Author: Juan Luis Cano Rodríguez

poliastro wishes everyone a merry new revolution around the Sun! 💫

During the December break, Juan Luis wrote [a new example on how to read OMM and TLE
data](https://docs.poliastro.space/en/latest/examples/Loading%20OMM%20and%20TLE%20satellite%20data.html)
that will help with a number of typical satellite observation use cases and
merged [a few refactors](https://github.com/poliastro/poliastro/pull/1434)
[and cleanups](https://github.com/poliastro/poliastro/pull/1430) of the source code.
We expect to make a 0.16.1 release soon to ship the documentation improvements,
and will keep cleaning up the code over the coming weeks and addressing some
long-standing issues.

In addition, Sebastian will kick off [the project to add array types to
poliastro](https://github.com/poliastro/documents/blob/master/numfocus-sdg-2021-r3.md)
very soon. This work will be possible thanks to the generous funding of
NumFOCUS, and will improve the performance of the library for some use cases.


text:
                Posted on

                by


text:
//@EliasHasle

function Structure(spec/*, ship*/) {
	//this.ship = ship;
	JSONSpecObject.call(this, spec);
}
Structure.prototype = Object.create(JSONSpecObject.prototype);
Object.assign(Structure.prototype, {
	setFromSpecification: function(spec) {
		this.hull = new Hull(spec.hull/*, this.ship*/);
		this.decks = spec.decks;/*{};
		let dspecs = spec.decks;
		let decks = this.decks;
		let dnames = Object.keys(dspecs);
		for (let i = 0; i < dnames.length; i++) {
			let name = dnames[i];
			let dspec = dspecs[name];
			decks[name] = new Deck(dspec,this.ship);
		}*/
		this.bulkheads = spec.bulkheads;/*{};
		let bhspecs = spec.bulkheads;
		let bulkheads = this.bulkheads;
		let bhnames = Object.keys(bhspecs);
		for (let i = 0; i < bhnames.length; i++) {
			let name = bhnames[i];
			let bhspec = bhspecs[name];
			bulkheads[name] = new Bulkhead(bhspec,this.ship);
		}*/

		return this;
	},
	getSpecification: function() {
		let spec = {
			hull: this.hull.getSpecification(),
			decks: this.decks,
			bulkheads: this.bulkheads
		};/*{decks: {}, bulkheads: {}};

		spec.hull = this.hull.getSpecification();

		let sd = spec.decks;
		let dk = Object.keys(this.decks);
		for (let i = 0; i < dk.length; i++) {
			sd[dk[i]] = this.decks[dk[i]].getSpecification();
		}

		let sbh = spec.bulkheads;
		let bhk = Object.keys(this.bulkheads);
		for (let i = 0; i < bhk.length; i++) {
			sbh[bhk[i]] = this.bulkheads[bhk[i]].getSpecification();
		}*/

		return spec;
	},
	//This is all dummy calculations
	getWeight: function(designState) {
		let components = [];
		//Hull
		components.push(this.hull.getWeight(designState));

		//structure:
		let decks = Object.values(this.decks);
		for (let i = 0; i < decks.length; i++) {
			let d = decks[i];
			let zc = d.zFloor + 0.5 * d.thickness;
			let yc = d.yCentre;
			let b = d.breadth;
			let wlc = this.hull.waterlineCalculation(zc, {minX: d.xAft, maxX: d.xFwd, minY: yc - 0.5 * b, maxY: yc + 0.5 * b});
			components.push({
				//approximation
				mass: wlc.Awp * d.thickness * d.density,
				cg: {
					x: wlc.xc,
					y: wlc.yc,
					z: zc
				}
			});
		}

		let bulkheads = Object.values(this.bulkheads);
		for (let i = 0; i < bulkheads.length; i++) {
			let bh = bulkheads[i];
			let xc = bh.xAft + 0.5 * bh.thickness;
			let sc = this.hull.stationCalculation(xc);
			components.push({
				//approximation
				mass: sc.A * bh.thickness * bh.density,
				cg: {
					x: xc,
					y: sc.yc,
					z: sc.zc
				}
			});
		}

		let output = combineWeights(components);
		//console.info("Total structural weight: ", output);
		return output;
	}
});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Factotum
{
	public partial class PipeScheduleView : Form
	{
		// ----------------------------------------------------------------------
		// Initialization
		// ----------------------------------------------------------------------

		// Form constructor
		public PipeScheduleView()
		{
			InitializeComponent();

			// Take care of settings that are not as easily managed in the designer.
			InitializeControls();
		}

		// Take care of the non-default DataGridView settings that are not as easily managed
		// in the designer.
		private void InitializeControls()
		{
		}

		// Set the status filter to show active tools by default
		// and update the tool selector combo box
		private void PipeScheduleView_Load(object sender, EventArgs e)
		{
			// Apply the current filters and set the selector row.
			// Passing a null selects the first row if there are any rows.
			UpdateSelector(null);
			// Now that we have some rows and columns, we can do some customization.
			CustomizeGrid();
			// Need to do this because the customization clears the row selection.
			SelectGridRow(null);
			// Wire up the handler for the Entity changed event
			EPipeSchedule.Changed += new EventHandler<EntityChangedEventArgs>(EPipeSchedule_Changed);
		}
		private void PipeScheduleView_FormClosed(object sender, FormClosedEventArgs e)
		{
			EPipeSchedule.Changed -= new EventHandler<EntityChangedEventArgs>(EPipeSchedule_Changed);
		}

		// ----------------------------------------------------------------------
		// Event Handlers
		// ----------------------------------------------------------------------
		// If any of this type of entity object was saved or deleted, we want to update the selector
		// The event args contain the ID of the entity that was added, mofified or deleted.
		void EPipeSchedule_Changed(object sender, EntityChangedEventArgs e)
		{
			UpdateSelector(e.ID);
		}

		// Handle the user's decision to edit the current tool
		private void EditCurrentSelection()
		{
			// Make sure there's a row selected
			if (dgvPipeSchedulesList.SelectedRows.Count != 1) return;

			Guid? currentEditItem = (Guid?)(dgvPipeSchedulesList.SelectedRows[0].Cells["ID"].Value);
			// First check to see if an instance of the form set to the selected ID already exists
			if (!Globals.CanActivateForm(this, "PipeScheduleEdit", currentEditItem))
			{
				// Open the edit form with the currently selected ID.
				PipeScheduleEdit frm = new PipeScheduleEdit(currentEditItem);
				frm.MdiParent = this.MdiParent;
				frm.Show();
			}
		}

		// This handles the datagridview double-click as well as button click
		void btnEdit_Click(object sender, System.EventArgs e)
		{
			EditCurrentSelection();
		}

		private void dgvPipeSchedulesList_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
				EditCurrentSelection();
		}

		// Handle the user's decision to add a new tool
		private void btnAdd_Click(object sender, EventArgs e)
		{
			PipeScheduleEdit frm = new PipeScheduleEdit();
			frm.MdiParent = this.MdiParent;
			frm.Show();
		}

		// Handle the user's decision to delete the selected tool
		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (dgvPipeSchedulesList.SelectedRows.Count != 1)
			{
				MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum");
				return;
			}
			Guid? currentEditItem = (Guid?)(dgvPipeSchedulesList.SelectedRows[0].Cells["ID"].Value);

			if (Globals.IsFormOpen(this, "PipeScheduleEdit", currentEditItem))
			{
				MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
				return;
			}

			EPipeSchedule PipeSchedule = new EPipeSchedule(currentEditItem);
			PipeSchedule.Delete(true);
			if (PipeSchedule.PipeScheduleErrMsg != null)
			{
				MessageBox.Show(PipeSchedule.PipeScheduleErrMsg, "Factotum");
				PipeSchedule.PipeScheduleErrMsg = null;
			}
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			Close();
		}

		// ----------------------------------------------------------------------
		// Private utilities
		// ----------------------------------------------------------------------
		// Update the tool selector combo box by filling its items based on current data and filters.
		// Then set the currently displayed item to that of the supplied ID.
		// If the supplied ID isn't on the list because of the current filter state, just show the
		// first item if there is one.
		private void UpdateSelector(Guid? id)
		{
			// Save the sort specs if there are any, so we can re-apply them
			SortOrder sortOrder = dgvPipeSchedulesList.SortOrder;
			int sortCol = -1;
			if (sortOrder != SortOrder.None)
				sortCol = dgvPipeSchedulesList.SortedColumn.Index;

			// Update the grid view selector
			DataView dv = EPipeSchedule.GetDefaultDataView();
			dgvPipeSchedulesList.DataSource = dv;
			// Re-apply the sort specs
			if (sortOrder == SortOrder.Ascending)
				dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns[sortCol], ListSortDirection.Ascending);
			else if (sortOrder == SortOrder.Descending)
				dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns[sortCol], ListSortDirection.Descending);

			// Select the current row
			SelectGridRow(id);
		}

		private void CustomizeGrid()
		{
			// Apply a default sort
			dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns["PipeScheduleSchedule"], ListSortDirection.Ascending);
			// Fix up the column headings
			dgvPipeSchedulesList.Columns["PipeScheduleSchedule"].HeaderText = "Schedule";
			dgvPipeSchedulesList.Columns["PipeScheduleNomDia"].HeaderText = "Nominal Diameter";
			dgvPipeSchedulesList.Columns["PipeScheduleOd"].HeaderText = "Outside Diameter";
			dgvPipeSchedulesList.Columns["PipeScheduleNomWall"].HeaderText = "Nominal Wall";
			// Hide some columns
			dgvPipeSchedulesList.Columns["ID"].Visible = false;
			dgvPipeSchedulesList.Columns["PipeScheduleIsLclChg"].Visible = false;
			dgvPipeSchedulesList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
		}

		// Select the row with the specified ID if it is currently displayed and scroll to it.
		// If the ID is not in the list,
		private void SelectGridRow(Guid? id)
		{
			bool found = false;
			int rows = dgvPipeSchedulesList.Rows.Count;
			if (rows == 0) return;
			int r = 0;
			DataGridViewCell firstCell = dgvPipeSchedulesList.FirstDisplayedCell;
			if (id != null)
			{
				// Find the row with the specified key id and select it.
				for (r = 0; r < rows; r++)
				{
					if ((Guid?)dgvPipeSchedulesList.Rows[r].Cells["ID"].Value == id)
					{
						dgvPipeSchedulesList.CurrentCell = dgvPipeSchedulesList[firstCell.ColumnIndex, r];
						dgvPipeSchedulesList.Rows[r].Selected = true;
						found = true;
						break;
					}
				}
			}
			if (found)
			{
				if (!dgvPipeSchedulesList.Rows[r].Displayed)
				{
					// Scroll to the selected row if the ID was in the list.
					dgvPipeSchedulesList.FirstDisplayedScrollingRowIndex = r;
				}
			}
			else
			{
				// Select the first item
				dgvPipeSchedulesList.CurrentCell = firstCell;
				dgvPipeSchedulesList.Rows[0].Selected = true;
			}
		}

	}
}


text:
<?php
namespace App\Modules\Articles\Models;

use App\Models\Model;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Notifications\Notifiable;
use App\Models\Image;
use App\Models\Filters;

class Article extends Model
{
    use Notifiable, Sortable, Image, Filters;

    public $filters = [
        'title'=> ['title', 'LIKE', '%?%']
    ];

    public function scopeOrder($query)
    {
        return $query->orderBy('priority', 'desc')->orderBy('date', 'desc');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SageFrame.SageFrameClass;
using SageFrame.Modules.Admin.HostSettings;
using SageFrame.Shared;
using SageFrame.Web;
using SageFrame.Localization;
using SageFrame.Framework;
using System.Collections.Specialized;

using SageFrame.Web.Utilities;
using Twitter;

public partial class Modules_Twitter_TwitterSettings : BaseAdministrationUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            imbSave.ImageUrl = GetTemplateImageUrl("btnsave.png", true);
            BindSettings();
        }
    }

    protected void BindSettings()
    {
        TwitterSettingsInfo twtData = new TwitterSettingsInfo();
        TwitterSqlhandler twtSql = new TwitterSqlhandler();
        int userModuuleID;
        bool status = int.TryParse(SageUserModuleID, out userModuuleID);
        twtData = twtSql.GetTwitterSettingValues(userModuuleID, GetPortalID);
        txtScreenName.Text = twtData.ScreenName.ToString();
        txtTwittsCount.Text = twtData.Count.ToString();
    }

    protected void imbSave_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            int PortalID = GetPortalID;
            string url = txtScreenName.Text;
            int userModuleID;
            bool status = int.TryParse(SageUserModuleID, out userModuleID);
            bool statuses;
            int count;
            statuses = int.TryParse(txtTwittsCount.Text, out count);
            TwitterSqlhandler twtSql = new TwitterSqlhandler();
            twtSql.SaveTwitterSettings(userModuleID.ToString(), GetPortalID.ToString(), "Tweets", url, count.ToString());
            ShowMessage(SageMessageTitle.Information.ToString(), SageMessage.GetSageModuleLocalMessageByVertualPath("Modules/TwitterDeck/ModuleLocalText", "TwitterSettingSavedSuccessfully"), "", SageMessageType.Success);
        }
        catch (Exception Ex)
        {
            ProcessException(Ex);
        }
    }
}


text:
DOC_FOLDER_NAME=loom-1.0-docs

make clean html
cd build
cp -r html/ $DOC_FOLDER_NAME
tar -czf $DOC_FOLDER_NAME.tar.gz $DOC_FOLDER_NAME
rm -r $DOC_FOLDER_NAME


text:
require 'api-tester/reporter/report'

module ApiTester
  # class for dealing with reports generated by the modules during test suite
  class ApiReport
    attr_accessor :reports

    def initialize
      self.reports = []
    end

    def add_new(url:, request:, expected_response:, actual_response:, description: 'case')
      report = Report.new description,
                          url,
                          request,
                          expected_response,
                          actual_response
      reports << report
    end

    def add_new_report(report)
      reports << report
    end

    def add_reports(reports)
      reports.each do |report|
        add_new_report(report)
      end
    end

    def print
      puts ''
      if reports.size.zero?
        puts 'No issues found'
      else
        puts "Issues discovered: #{reports.size}"
        reports.each do |report|
          report.print
          puts ''
          puts ''
        end
        puts "Total issues: #{reports.size}"
      end
    end
  end
end


text:
@implementation NSArray (TOCInternal_Functional)

-(NSArray*) map:(TOCInternal_Projection)projection {
    TOCInternal_need(projection != nil);

    NSMutableArray* results = [NSMutableArray arrayWithCapacity:self.count];
    for (id item in self) {
        id projectedItem = projection(item);
        TOCInternal_need(projectedItem != nil);
        [results addObject:projectedItem];
    }

    return [results copy]; // remove mutability
}

-(NSArray*) where:(TOCInternal_Predicate)predicate {
    TOCInternal_need(predicate != nil);

    NSMutableArray* results = [NSMutableArray arrayWithCapacity:self.count];
    for (id item in self) {
        if (predicate(item)) {
            [results addObject:item];
        }
    }

    return [results copy]; // remove mutability
}

-(bool) allItemsSatisfy:(TOCInternal_Predicate)predicate {
    TOCInternal_need(predicate != nil);

    for (id item in self) {
        if (!predicate(item)) {
            return false;
        }
    }
    return true;
}

-(bool) allItemsAreKindOfClass:(Class)classInstance {
    TOCInternal_need(classInstance != nil);
    return [self allItemsSatisfy:^bool(id value) { return [value isKindOfClass:classInstance]; }];
}

@end


text:
Solves two problems:

 - Warns users when two people are editing the same object in the Django admin.
 - Autosaves the changes to firebase in real time and notifies the user if there are unsaved changes.
 If the user leaves the page for some reason, they can see their unsaved changes and apply them to the form.

## The main problem

When two users are editing the same Django admin page at the same time, it is almost
inevitable that one of the users will override the other's changes.

Flame is the simplest solution to prevent this problem.

## The solution

Use a pub-sub server to track active users and notify others when a change occurs.

![save-notification](/docs/images/save-notification.png)

## Autosave!

Many people use Django for content editing purposes. The biggest nightmare for an editor is to accidentally
close the browser and lose all his work.

Modern web apps (Gmail, Google docs, etc.) already support autosave and lack of this feature in sites built with Django create a bad experience for the users.

#### No need to setup Tornado or a similar pubsub server.

Flame uses Firebase as the pubsub provider. Firebase is quite reliable and the free tier already supports up to 50 connections which should be enough for an admin site.

### How does it work?

Flame syncs the contents of the change form regularly with Firebase. When the user saves the form, it deletes this data from Firebase.

However if the user leaves the page without saving the form, the unsaved data stays in the Firebase data store.

When the user reloads that page, he sees a notification box that says "You have unsaved changes." The user can choose to apply the changes to the form or ignore (and delete) this content forever.

# Setting up

```
pip install django-suit-flame
```

Add suit_flame *before* django-suit into the INSTALLED_APPS setting

```
INSTALLED_APPS = (
    'suit_flame',
    'suit',
```

Create a new Firebase data store and add necessary keys to settings.py:

```
FLAME_AUTOSAVE = True
FLAME_FIREBASE_SUBDOMAIN = 'https://example-subdomain-136.firebaseio.com'
FLAME_FIREBASE_SECRET_KEY = 'e22bA3KOg54gfwr9lmoWyi1sg8dL8uwOg8txRyfl2'
```

Make sure to add necessary security settings at Firebase.

Go to your Firebase project settings and update the Security & Rules section with these ones:

```
{
    "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
    }
}
```

This will ensure the privacy of your data.

# Contributors

 -  [Umit Dincel](https://github.com/umitdincel)
 -  [Yigit Guler](https://github.com/yigitguler)

Made by [Hipo](http://hipolabs.com)


text:
import {
	Object3D,
	Scene,
	Camera
} from '../../../src/Three';

export class CSS3DObject extends Object3D {

	constructor( element: HTMLElement );
	element: HTMLElement;

	onBeforeRender: ( renderer: unknown, scene: Scene, camera: Camera ) => void;
	onAfterRender: ( renderer: unknown, scene: Scene, camera: Camera ) => void;

}

export class CSS3DSprite extends CSS3DObject {

	constructor( element: HTMLElement );

}

export class CSS3DRenderer {

	constructor();
	domElement: HTMLElement;

	getSize(): { width: number, height: number };
	setSize( width: number, height: number ): void;
	render( scene: Scene, camera: Camera ): void;

}


text:
@implementation SBContact

@synthesize address = _address;
@synthesize altEmail = _altEmail;
@synthesize blog = _blog;
@synthesize department = _department;
@synthesize email = _email;
@synthesize facebook = _facebook;
@synthesize fax = _fax;
@synthesize firstName = _firstName;
@synthesize lastName = _lastName;
@synthesize linkedIn = _linkedIn;
@synthesize mobile = _mobile;
@synthesize phone = _phone;
@synthesize source = _source;
@synthesize title = _title;
@synthesize twitter = _twitter;
@synthesize birthDate = _birthDate;
@synthesize doNotCall = _doNotCall;

#pragma mark -
#pragma mark Static methods

+ (NSString *)serverPath
{
    return @"contacts";
}

+ (NSArray *)displayedProperties
{
    static NSArray *properties;
    if (properties == nil)
    {
        properties = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:kABPersonFirstNameProperty],
                      [NSNumber numberWithInt:kABPersonLastNameProperty],
                      [NSNumber numberWithInt:kABPersonJobTitleProperty],
                      [NSNumber numberWithInt:kABPersonDepartmentProperty],
                      [NSNumber numberWithInt:kABPersonBirthdayProperty],
                      [NSNumber numberWithInt:kABPersonPhoneProperty],
                      [NSNumber numberWithInt:kABPersonURLProperty],
                      [NSNumber numberWithInt:kABPersonEmailProperty],
                      nil];
    }
    return properties;
}

#pragma mark -
#pragma mark Init and dealloc

- (id)initWithTBXMLElement:(TBXMLElement *)element
{
    if (self = [super initWithTBXMLElement:element])
    {
        self.photoURL = nil;
        self.address = [SBBaseEntity stringValueForElement:@"address" parentElement:element];
        self.altEmail = [SBBaseEntity stringValueForElement:@"alt-email" parentElement:element];
        self.blog = [SBBaseEntity stringValueForElement:@"blog" parentElement:element];
        self.birthDate = [self.formatter dateFromString:[SBBaseEntity stringValueForElement:@"born-on"
                                                                            parentElement:element]];
        self.department = [SBBaseEntity stringValueForElement:@"department" parentElement:element];
        self.doNotCall = [[SBBaseEntity stringValueForElement:@"do-not-call" parentElement:element] isEqualToString:@"true"];
        self.email = [SBBaseEntity stringValueForElement:@"email" parentElement:element];
        self.facebook = [SBBaseEntity stringValueForElement:@"facebook" parentElement:element];
        self.fax = [SBBaseEntity stringValueForElement:@"fax" parentElement:element];
        self.firstName = [SBBaseEntity stringValueForElement:@"first-name" parentElement:element];
        self.lastName = [SBBaseEntity stringValueForElement:@"last-name" parentElement:element];
        self.linkedIn = [SBBaseEntity stringValueForElement:@"linkedin" parentElement:element];
        self.mobile = [SBBaseEntity stringValueForElement:@"mobile" parentElement:element];
        self.phone = [SBBaseEntity stringValueForElement:@"phone" parentElement:element];
        self.source = [SBBaseEntity stringValueForElement:@"source" parentElement:element];
        self.title = [SBBaseEntity stringValueForElement:@"title" parentElement:element];
        self.twitter = [SBBaseEntity stringValueForElement:@"twitter" parentElement:element];

        NSString *serverURL = [SBSettingsManager sharedSBSettingsManager].server;
        NSString *defaultImage = [NSString stringWithFormat:@"%@/images/avatar.jpg", serverURL];
        self.photoURL = [[[NSURL alloc] initWithString:defaultImage] autorelease];

        if (self.email != nil)
        {
            NSString *emailHash = [self.email md5];
            NSString *base = @"http://www.gravatar.com/avatar";
            defaultImage = [self.photoURL cacheKey];
            NSString *stringURL = [NSString stringWithFormat:@"%@/%@.png?d=%@&s=50", base, emailHash, defaultImage];
            self.photoURL = [[[NSURL alloc] initWithString:stringURL] autorelease];
        }
    }
    return self;
}

- (id)initWithPerson:(ABRecordRef)person
{
    self = [super init];
    if (self)
    {
        _person = CFRetain(person);

        self.firstName = getPersonPropertyValue(person, kABPersonFirstNameProperty, NULL);
        self.lastName = getPersonPropertyValue(person, kABPersonLastNameProperty, NULL);
        self.title = getPersonPropertyValue(person, kABPersonJobTitleProperty, NULL);
        self.department = getPersonPropertyValue(person, kABPersonDepartmentProperty, NULL);

        CFDateRef birthday = ABRecordCopyValue(person, kABPersonBirthdayProperty);
        self.birthDate = (NSDate *)birthday;
        CFRelease(birthday);

        self.mobile = getPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneMobileLabel);
        self.phone = getPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneMainLabel);
        self.fax = getPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneWorkFAXLabel);
        self.blog = getPersonPropertyValue(_person, kABPersonURLProperty, kABPersonHomePageLabel);
        self.email = getPersonPropertyValue(_person, kABPersonEmailProperty, kABWorkLabel);
        self.altEmail = getPersonPropertyValue(_person, kABPersonEmailProperty, kABHomeLabel);
    }
    return self;
}

- (void)dealloc
{
    [_address release];
    [_altEmail release];
    [_blog release];
    [_department release];
    [_email release];
    [_facebook release];
    [_fax release];
    [_firstName release];
    [_lastName release];
    [_linkedIn release];
    [_mobile release];
    [_phone release];
    [_source release];
    [_title release];
    [_twitter release];
    [_birthDate release];

    if (_person != NULL)
    {
        CFRelease(_person);
    }
    [super dealloc];
}

#pragma mark -
#pragma mark Overridden methods

- (NSString *)description
{
    NSMutableString *result = [[NSMutableString alloc] init];
    if ([self.title length] > 0)
    {
        [result appendString:self.title];
    }
    if ([self.department length] > 0)
    {
        if ([result length] > 0)
        {
            [result appendString:@" - "];
        }
        [result appendString:self.department];
    }
    if ([self.phone length] > 0)
    {
        if ([result length] > 0)
        {
            [result appendString:@" - "];
        }
        [result appendString:self.phone];
    }
    if ([self.email length] > 0)
    {
        if ([result length] > 0)
        {
            [result appendString:@" - "];
        }
        [result appendString:self.email];
    }

    return [result autorelease];
}

- (NSString *)name
{
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

#pragma mark -
#pragma mark Dynamic properties

- (ABRecordRef)getPerson
{
    if (_person == NULL)
    {
        _person = ABPersonCreate();
        ABRecordSetValue(_person, kABPersonFirstNameProperty, self.firstName, nil);
        ABRecordSetValue(_person, kABPersonLastNameProperty, self.lastName, nil);

        if ([self.title length] > 0)
        {
            ABRecordSetValue(_person, kABPersonJobTitleProperty, self.title, nil);
        }

        if ([self.department length] > 0)
        {
            ABRecordSetValue(_person, kABPersonDepartmentProperty, self.department, nil);
        }

        ABRecordSetValue(_person, kABPersonBirthdayProperty, [self.birthDate stringWithDateFormattedWithCurrentLocale], nil);

        setPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneMobileLabel, self.mobile);
        setPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneMainLabel, self.phone);
        setPersonPropertyValue(_person, kABPersonPhoneProperty, kABPersonPhoneWorkFAXLabel, self.fax);
        setPersonPropertyValue(_person, kABPersonURLProperty, kABPersonHomePageLabel, self.blog);
        setPersonPropertyValue(_person, kABPersonEmailProperty, kABWorkLabel, self.email);
        setPersonPropertyValue(_person, kABPersonEmailProperty, kABHomeLabel, self.altEmail);

        NSString *key = [self.photoURL cacheKey];
        UIImage *image = [[AKOImageCache sharedAKOImageCache] imageForKey:key];
        if (image != nil)
        {
            NSData *data = UIImagePNGRepresentation(image);
            CFDataRef cfdata = (CFDataRef)data;
            CFErrorRef error;
            ABPersonSetImageData(_person, cfdata, &error);
        }
    }

    return _person;
}

- (NSString *)commentableTypeName
{
    return @"Contact";
}

@end


text:
  Doncourt-lès-Conflans est
      une ville géographiquement positionnée dans le département de Meurthe-et-Moselle en Lorraine. Elle totalisait 1 282 habitants en 2008.

À Doncourt-lès-Conflans, la valeur moyenne à la vente d'un appartement s'évalue à 292 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 904 € du m². À la location la valeur moyenne se situe à 6,21 € du m² mensuel.

À proximité de Doncourt-lès-Conflans sont positionnées géographiquement les communes de
Vernéville située à 5 km, 598 habitants,
Labry localisée à 4 km, 1 659 habitants,
Giraumont située à 3 km, 1 178 habitants,
Hatrize localisée à 5 km, 729 habitants,
Jouaville située à 2 km, 290 habitants,
Batilly localisée à 4 km, 1 297 habitants,
 entre autres. De plus, Doncourt-lès-Conflans est située à seulement 17 km de Metz.

La ville compte quelques  équipements, elle dispose, entre autres, de un terrain de sport.

Le parc d'habitations, à Doncourt-lès-Conflans, était réparti en 2011 en 54 appartements et 385 maisons soit
 un marché relativement équilibré.


text:
<?php

namespace Mondel\CuentaloBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Response;

use Mondel\CuentaloBundle\Entity\Contenido,
    Mondel\CuentaloBundle\Entity\Comentario,
    Mondel\CuentaloBundle\Entity\Notificacion,
    Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion,
    Mondel\CuentaloBundle\Entity\Voto;
use Mondel\CuentaloBundle\Form\Type\ContenidoType,
    Mondel\CuentaloBundle\Form\Type\ComentarioType;
use Mondel\CuentaloBundle\Helpers\StringHelper;

class ContenidoController extends Controller
{

    public function crearAction()
    {
        $peticion = $this->getRequest();

        $contenido = new Contenido();

        $formulario = $this->createForm(new ContenidoType(), $contenido);
        $formulario->bindRequest($peticion);

        if ($formulario->isValid()) {
            $contenido->setIp($peticion->getClientIp());
            $contenido->setTexto(
                StringHelper::limpiar_malas_palabras(
                    $contenido->getTexto()
                )
            );

            $em = $this->getDoctrine()->getEntityManager();
            if ($this->get('security.context')->isGranted("ROLE_USER")) {
                $usuario = $this->get('security.context')->getToken()->getUser();
                $contenido->setUsuario($usuario);

                $suscripcion = new UsuarioContenidoSuscripcion();
                $suscripcion->setUsuario($usuario);
                $suscripcion->setContenido($contenido);
                $em->persist($suscripcion);
            }

            $em->persist($contenido);
            $em->flush();
        }

        //TODO: Perdi los errores del formulario
        return $this->redirect($this->generateUrl('_inicio'));
    }

    public function comentarAction($id)
    {
        $peticion = $this->getRequest();
        $manager = $this->getDoctrine()->getEntityManager();

       	if (false === $this->get('security.context')->isGranted('ROLE_USER'))
            throw new AccessDeniedException();

        $contenido = $manager->getRepository('MondelCuentaloBundle:Contenido')->find($id);

        if (!$contenido)
            throw $this->createNotFoundException('El post que intentas comentar no existe');

        $comentario = new Comentario();
        $formulario = $this->createForm(new ComentarioType(), $comentario);

        $formulario->bindRequest($peticion);

        if ($formulario->isValid()) {

            $comentario->setIp($peticion->getClientIp());
            $usuario = $this->get('security.context')->getToken()->getUser();
            $comentario->setUsuario($usuario);
            $comentario->setContenido($contenido);

            $comentario->setTexto(
                StringHelper::limpiar_malas_palabras(
                    $comentario->getTexto()
                )
            );

            $query_builder = $manager->createQueryBuilder();
            $query_builder->add('select', 's')
                ->add('from', 'Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion s')
                ->add('where', 's.usuario = ?1 and s.contenido = ?2')
                ->setParameters(array(1 => $usuario, 2 => $contenido));

            if (count($query_builder->getQuery()->getArrayResult()) == 0) {
                $suscripcion = new UsuarioContenidoSuscripcion();
                $suscripcion->setUsuario($usuario);
                $suscripcion->setContenido($contenido);
                $manager->persist($suscripcion);
            }

            $query_builder = $manager->createQueryBuilder();
            $query_builder->add('select', 's')
                ->add('from', 'Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion s')
                ->add('where', 's.contenido = ?1 and s.usuario != ?2')
                ->setParameters(array(1 => $contenido, 2 => $usuario));

            foreach($query_builder->getQuery()->getResult() as $suscripcion) {
                $notificacion = new Notificacion();
                $notificacion->setUsuarioContenidoSuscripcion($suscripcion);
                $notificacion->setTexto($usuario->getNick() . ' ha comentado la publicación #' . $contenido->getId());
                $notificacion->setLeida(false);
                $manager->persist($notificacion);

                if ($suscripcion->getUsuario()->getRecibeNotificaciones())
                {
                    $mensaje = \Swift_Message::newInstance()
                        ->setSubject('Cuentalo: tienes una nueva notificación')
                        ->setFrom(array('notificaciones@cuentalo.com.uy' => 'www.cuentalo.com.uy'))
                        ->setTo($suscripcion->getUsuario()->getEmail())
                        ->setBody($this->renderView(
                                'MondelCuentaloBundle:Usuario:emailNotificacion.html.twig',
                                array(
                                    'notificacion' => $notificacion,
                                )
                        ), 'text/html')
                    ;
                    $this->get('mailer')->send($mensaje);
                }
            }

            $manager->persist($comentario);
            $manager->flush();
        }
        return $this->redirect($this->generateUrl(
                '_contenido_pagina_mostrar',
                array('id' => $id)
        ));
    }

    public function comentarAjaxAction($id, $offset)
    {
        $peticion = $this->getRequest();
        $manager = $this->getDoctrine()->getEntityManager();

        if (false === $this->get('security.context')->isGranted('ROLE_USER'))
            throw new AccessDeniedException();

        $contenido = $manager->getRepository('MondelCuentaloBundle:Contenido')->find($id);

        if (!$contenido)
            throw $this->createNotFoundException('El post que intentas comentar no existe');

        $comentario = new Comentario();
        $formulario = $this->createForm(new ComentarioType(), $comentario);

        $formulario->bindRequest($peticion);

        if ($formulario->isValid()) {

            $comentario->setIp($peticion->getClientIp());
            $usuario = $this->get('security.context')->getToken()->getUser();
            $comentario->setUsuario($usuario);
            $comentario->setContenido($contenido);

            $comentario->setTexto(
                StringHelper::limpiar_malas_palabras(
                    $comentario->getTexto()
                )
            );

            $query_builder = $manager->createQueryBuilder();
            $query_builder->add('select', 's')
                ->add('from', 'Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion s')
                ->add('where', 's.usuario = ?1 and s.contenido = ?2')
                ->setParameters(array(1 => $usuario, 2 => $contenido));

            if (count($query_builder->getQuery()->getArrayResult()) == 0) {
                $suscripcion = new UsuarioContenidoSuscripcion();
                $suscripcion->setUsuario($usuario);
                $suscripcion->setContenido($contenido);
                $manager->persist($suscripcion);
            }

            $query_builder = $manager->createQueryBuilder();
            $query_builder->add('select', 's')
                ->add('from', 'Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion s')
                ->add('where', 's.contenido = ?1 and s.usuario != ?2')
                ->setParameters(array(1 => $contenido, 2 => $usuario));

            foreach($query_builder->getQuery()->getResult() as $suscripcion) {
                $notificacion = new Notificacion();
                $notificacion->setUsuarioContenidoSuscripcion($suscripcion);
                $notificacion->setTexto($usuario->getNick() . ' ha comentado la publicación #' . $contenido->getId());
                $notificacion->setLeida(false);
                $manager->persist($notificacion);

                if ($suscripcion->getUsuario()->getRecibeNotificaciones())
                {
                    $mensaje = \Swift_Message::newInstance()
                        ->setSubject('Cuentalo: tienes una nueva notificación')
                        ->setFrom(array('notificaciones@cuentalo.com.uy' => 'www.cuentalo.com.uy'))
                        ->setTo($suscripcion->getUsuario()->getEmail())
                        ->setBody($this->renderView(
                                'MondelCuentaloBundle:Usuario:emailNotificacion.html.twig',
                                array(
                                    'notificacion' => $notificacion,
                                )
                        ), 'text/html')
                    ;
                    $this->get('mailer')->send($mensaje);
                }
            }

            $manager->persist($comentario);
            $manager->flush();
        }
        return $this->render(
                'MondelCuentaloBundle:Contenido:comentariosMostrar.html.twig',
                array(
                        'offset' => $offset,
                        'contenido'  => $contenido,
                        'formularios_comentarios' => array($id => $formulario->createView())
                )
        );
    }

    public function comentarioEliminarAction($id)
    {
    	$manager = $this->getDoctrine()->getEntityManager();
    	$comentario = $manager->getRepository('MondelCuentaloBundle:Comentario')->find($id);

		if (false === $this->get('security.context')->isGranted('ROLE_USER'))
            throw new AccessDeniedException();

    	if (!$comentario)
    		throw $this->createNotFoundException('El comentario que intentas eliminar no existe');

    	$contenido = $comentario->getContenido();
        $usuario = $comentario->getUsuario();

    	if ($this->get('security.context')->getToken()->getUser()->getId() == $usuario->getId()) {
    		$manager->remove($comentario);
            // Compruebo si tiene una suscripcion a ese contenido, y borro su unico comentario
            // elimino la suscripcion tambien
            if ($contenido->getUsuario() != null && $contenido->getUsuario()->getId() != $usuario->getId()) {
                $query_builder = $manager->createQueryBuilder();
                $query_builder->add('select', 'c')
                    ->add('from', 'Mondel\CuentaloBundle\Entity\Comentario c')
                    ->add('where', 'c.usuario = ?1 and c.contenido = ?2')
                    ->setParameters(array(1 => $usuario, 2 => $contenido));

                if (count($query_builder->getQuery()->getArrayResult()) == 1) {
                    $query_builder = $manager->createQueryBuilder();
                    $query_builder->add('select', 's')
                        ->add('from', 'Mondel\CuentaloBundle\Entity\UsuarioContenidoSuscripcion s')
                        ->add('where', 's.usuario = ?1 and s.contenido = ?2')
                        ->setParameters(array(1 => $usuario, 2 => $contenido));
                    $suscripcion = $query_builder->getQuery()->getSingleResult();

                    foreach($suscripcion->getNotificaciones() as $notificacion) {
                        $manager->remove($notificacion);
                    }

                    $manager->remove($suscripcion);
                }
            }
            $manager->flush();

            if (!$this->getRequest()->isXmlHttpRequest()) {
                $this->get('session')->setFlash('notice', 'Se ha eliminado el comentario correctamente');
            }
    	} else {
    		throw $this->createNotFoundException('El comentario que intentas eliminar no es tuyo');
    	}
        if ($this->getRequest()->isXmlHttpRequest()) {
            return new Response('Se ha eliminado el comentario correctamente');
        } else {
            return $this->redirect($this->generateUrl(
        			'_contenido_pagina_mostrar',
        			array('id' => $contenido->getId())
        	));
        }
    }

    public function paginaMostrarAction($id)
    {
        $contenido = $this->getDoctrine()->getRepository('MondelCuentaloBundle:Contenido')->find($id);

        if (!$contenido || !$contenido->getActivo())
            throw $this->createNotFoundException('El post que intentas ver no existe o esta desactivado');

        $comentario = new Comentario();
        $formulario = $this->createForm(new ComentarioType(), $comentario);

        if ($this->get('security.context')->isGranted('ROLE_USER')) {
            $usuario = $this->get('security.context')->getToken()->getUser();
            if ($usuario->estaSuscritoContenido($id)) {
                $this->getDoctrine()->getRepository('MondelCuentaloBundle:Usuario')->marcarNotificacionesComoLeidas($usuario->getId(), $id);
            }
        }

        return $this->render(
            'MondelCuentaloBundle:Contenido:paginaMostrar.html.twig',
            array(
                'contenido'  => $contenido,
                'formularios_comentarios' => array($id => $formulario->createView())
            )
        );
    }

    public function mostrarAction($id)
    {
    	$contenido = $this->getDoctrine()->getRepository('MondelCuentaloBundle:Contenido')->find($id);

    	if (!$contenido)
    		throw $this->createNotFoundException('El post que intentas ver no existe');

    	$comentario = new Comentario();
    	$formulario = $this->createForm(new ComentarioType(), $comentario);

    	return $this->render(
    			'MondelCuentaloBundle:Contenido:mostrar.html.twig',
    			array(
    					'contenido'  => $contenido,
    					'formularios_comentarios' => array($id => $formulario->createView())
    			)
    	);
    }

    public function listarAction($categoria,$inicio,$cantidad)
    {
        $manager = $this->getDoctrine()->getEntityManager();

        $query_builder = $manager->createQueryBuilder();

        if ($categoria == '0') {
	        $query_builder->add('select', 'c')
	        	->add('from', 'Mondel\CuentaloBundle\Entity\Contenido c')
	        	->add('where', 'c.activo = ?1 and c.id < ?2')
	        	->add('orderBy', 'c.fecha_creacion DESC')
	        	->setMaxResults($cantidad)
	        	->setParameters(array(1 => 1, 2 => $inicio));
        } else {
        	$query_builder->add('select', 'c')
	        	->add('from', 'Mondel\CuentaloBundle\Entity\Contenido c')
	        	->add('where', 'c.activo = ?1 and c.id < ?2 and c.categoria = ?3')
	        	->add('orderBy', 'c.fecha_creacion DESC')
	        	->setMaxResults($cantidad)
	        	->setParameters(array(
	        			1 => 1,
	        			2 => $inicio,
	        			3 => $this->getDoctrine()->getRepository('MondelCuentaloBundle:Categoria')->find($categoria)
	        			));
        }

        $contenidos = $query_builder->getQuery()
        	->getResult();

        // Creo los formularios de comentarios para cada contenido
        $formularios_comentarios = array();
        foreach ($contenidos as $contenido) {
        	$comentario = new Comentario();
        	$formulario_comentario = $this->createForm(new ComentarioType(), $comentario);
        	$formularios_comentarios[$contenido->getId()] = $formulario_comentario->createView();
        }

        return $this->render(
            'MondelCuentaloBundle:Contenido:listar.html.twig',
            array(
            		'contenidos' => $contenidos,
            		'formularios_comentarios' => $formularios_comentarios
            		)
        );

    }

    public function categoriaListarAction($categoria)
    {
    	$categoria = $this->getDoctrine()
    		->getRepository('MondelCuentaloBundle:Categoria')
    			->findOneBy(array('nombre' => $categoria));

    	if (!$categoria)
    		throw $this->createNotFoundException('Esta categoría no existe');

    	$manager = $this->getDoctrine()->getEntityManager();

    	$query_builder = $manager->createQueryBuilder();

    	$query_builder->add('select', 'c')
    		->add('from', 'Mondel\CuentaloBundle\Entity\Contenido c')
    		->add('where', 'c.activo = ?1 and c.categoria = ?2')
    		->add('orderBy', 'c.fecha_creacion DESC')
    		->setMaxResults(5)
    		->setParameters(array(1 => 1, 2 => $categoria));

    	$contenidos = $query_builder->getQuery()
    		->getResult();

    	// Creo los formularios de comentarios para cada contenido
    	$formularios_comentarios = array();
    	foreach ($contenidos as $contenido) {
    		$comentario = new Comentario();
    		$formulario_comentario = $this->createForm(new ComentarioType(), $comentario);
    		$formularios_comentarios[$contenido->getId()] = $formulario_comentario->createView();
    	}

    	// Creo el formulario para pasarle al crear de Contenido
    	$contenido = new Contenido();
    	$formulario_contenido = $this->createForm(new ContenidoType(), $contenido);

    	return $this->render(
    			'MondelCuentaloBundle:Default:inicio.html.twig',
    			array(
                        'pagina_titulo' => $categoria->getNombre(),
    					'contenidos'    => $contenidos,
    					'form'          => $formulario_contenido->createView(),
    					'formularios_comentarios' => $formularios_comentarios,
    					'cid'			=> $categoria->getId()
    			)
    	);

    }

    public function votarAction($id)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_USER')) {
            throw new AccessDeniedException();
        } else {

            $contenido = $this->getDoctrine()
                    ->getRepository('MondelCuentaloBundle:Contenido')
                    ->find($id);

            if (!$contenido) {
                throw $this->createNotFoundException('No existe ese contenido '.$id);
            }

            $voto = new Voto();
            $voto->setContenido($contenido);

            $request = $this->getRequest();
            $voto->setIp($request->getClientIp());

            $usuario = $this->get('security.context')->getToken()->getUser();
            $voto->setUsuario($usuario);

            foreach ($contenido->getVotos() as $_voto) {
                if ($voto->getUsuario()->getUsername() == $_voto->getUsuario()->getUsername()) {
                    throw $this->createNotFoundException('Error, usted ya ha votado');
                }
            }

            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($voto);
            $em->flush();
        }

        return $this->redirect($this->generateUrl(
                'vista_contenido',
                array(
                    'id'     => $contenido->getId(),
                    'tipo'   => $contenido->getTipo()
                )
        ));

    }

}


text:
package com.jem.util;

import java.awt.image.BufferedImage;
import java.util.stream.IntStream;

/**
 * Images
 *

 * A utility class for modifying, converting, and creating images.
 *
 * @author Ian Caffey
 * @since 1.04
 */
public class Images {
    private Images() {
    }

    /**
     * Converts a BufferedImage to a raw int[][] representing each pixel's rgb value.
     *
     * @param image the image to convert
     * @return an int[][] representing the underlying buffer of the BufferedImage
     */
    public static int[][] toBuffer(BufferedImage image) {
        if (image == null)
            throw new IllegalArgumentException();
        int width = image.getWidth();
        int height = image.getHeight();
        int[][] buffer = new int[height][width];
        IntStream.range(0, buffer.length).forEach(y -> IntStream.range(0, buffer[y].length).forEach(x -> buffer[y][x] = image.getRGB(x, y)));
        return buffer;
    }

    /**
     * Creates a BufferedImage using a int[][] which represents the underlying raster.
     * Defaults to use BufferedImage.TYPE_INT_ARGB as the image type.
     *
     * @param buffer the image to convert
     * @return an int[][] representing the underlying buffer of the BufferedImage
     */
    public static BufferedImage toImage(int[][] buffer) {
        return toImage(buffer, BufferedImage.TYPE_INT_ARGB);
    }

    /**
     * Creates a BufferedImage using a int[][] which represents the underlying raster.
     *
     * @param buffer the image to convert
     * @return an int[][] representing the underlying buffer of the BufferedImage
     */
    public static BufferedImage toImage(int[][] buffer, int imageType) {
        if (buffer == null)
            throw new IllegalArgumentException();
        BufferedImage image = new BufferedImage(buffer[0].length, buffer.length, imageType);
        IntStream.range(0, buffer.length).forEach(y -> IntStream.range(0, buffer[y].length).forEach(x -> image.setRGB(x, y, buffer[y][x])));
        return image;
    }
}


text:
_Podcatching for nerds_

Poddb lets you browse, search, and download podcasts from the Unix command line
and Vim.

[screenshots]

With Poddb, you can power-browse all of NPR's recent podcasts with the command,

    poddb npr

and all recent TED talks with the command,

    poddb tedtalks

## Why

I wanted a fast and lightweight way to search for and download podcasts in any
Unix environment, without resorting to a GUI application or web browser.  I
also wanted to start crowdsourcing and publishing podcast download statistics
to make it easier to spot popular podcasts and podcast episodes. Finally, I
wanted a more streamlined way to search for NPR podcasts than through the NPR
website or iTunes. Poddb serves these three goals.

## Prerequisites

* Vim (7.2 or later)
* Ruby 1.9.x
* wget
* curl
* mplayer, iTunes, or other media player

To install Ruby 1.9.2, I recommend using the [RVM Version Manager][rvm].

[rvm]:http://rvm.beginrescueend.com

Poddb assumes a Unix (POSIX) environment.

## Install

Poddb can be installed as a Ruby gem. Please note that while the tool is called
**poddb**, the gem is called **poddb_client**.

    gem install poddb_client

Test your installation by typing `poddb -h`. You should see poddb's help.

On some systems you may run into a PATH issue, where the system can't find the
`poddb` command after installation. You might want to try

    sudo gem install poddb_client

to see if that puts `poddb` on your PATH.

If you ever want to uninstall Poddb from your system, just execute this command:

    gem uninstall poddb_client

This will remove all traces of Poddb, except for the application-specific files
it creates in a directory called `~/.poddb`. These you'll have to remove
manually.

To update Poddb to the latest version, just run `gem install poddb_client`
again.

## How to use it

You invoke `poddb` from command line interface, passing it flags and search
terms. Poddb will send the query over the internet to the Poddb server. (So you
must be online to use Poddb, though once you've downloaded some podcast audio
or video files you can play them entirely offline.) The server will send back
data, and Poddb will launch Vim to let you navigate and interact with the query
results.

Here is a partial synopsis of the command line interface. A more detailed guide
to using Poddb follows.

    Usage: poddb [options] [query]

        -f, --from-favorites             Show all recent episodes from favorite podcasts
        -a, --add PODCAST_URL            Add podcast with PODCAST_URL to the poddb database
        -l, --list [QUERY]               List all podcasts in the poddb database
                                         (If QUERY is supplied, will return matching podcasts)
        -F, --favorite-podcasts          Show favorite podcasts
        -o, --order ORDER                Sort results by ORDER
                                         The only option right now is 'popular'. Default order is pubdate.
        -d, --days DAYS                  Limit results to episodes published since DAYS days ago
        -t, --type MEDIA_TYPE            Return episodes of MEDIA_TYPE only (audio,video)

## Browse and search for podcasts

To see all the podcasts in the poddb database:

    poddb -l

Type `poddb -l QUERY` to see if any podcasts matching the QUERY string are in
the database. E.g.

    poddb -l music

will return all the podcasts in the Poddb database with the word "music" in the
title or podcast description.

Press `ENTER` on a podcast to see its episodes.  See below for instructions on
how to view and download episodes.

## Add podcasts to the database

If you don't see a favorite podcast of yours in the list returned by `poddb -l`,
you can add the podcast to the Poddb database with this command:

    poddb -a PODCAST_URL

E.g.,

    poddb -a http://www.philosophybites.libsyn.com/rss

The `-a` command will also add the podcast to your favorites.

## Search for podcast episodes

With Poddb, you search for podcast episodes from the command line. If there are
matches, Poddb will launch the Vim navigation interface. If not, you'll just
see a message saying no matches were found.

A basic search like

    poddb music oud

will return all podcast episodes that match the query words "music" and "oud."

    pubdate      | match | dwnlds | title                                              | podcast
    -------------+-------+--------+----------------------------------------------------+--------------------
    Sep 01 2011  |  0.99 |      1 | Journeys with the Oud                              | PRI: Afropop Worldw
    Aug 05 2011  |  8.74 |        | Mystics and the Mediterranean (Podcast Edition)    | The latest articles
    Jun 29 2011  |  1.01 |        | Worldview 6.29.11                                  | Worldview Podcast
    Oct 15 2010  |  0.97 |        | Unusual Collaborations (Weekly Podcast)            | The latest articles

You can also limit the scope of the search by media type:

    poddb -t video ruby

will return all podcast episodes that match the word "ruby" that are video
downloads.

You can use `-t audio` to limit search results to audio downloads.

Note that the (video|audio) options don't always filter correctly because some
feeds give videos the media type 'audio/mpeg'. These videos won't show up in
the current version of Poddb if you use the `-t video` flag.

Two other command flags that are useful are `-o` and `-d`. `-d n` lets you
limit the scope of the search to episodes published in the last _n_ days. So

    poddb -d 7 libya

will return all podcast episodes that match the query "libya" published over
the last week.

To sort the search results by most popular episodes first, use the `-o popular`
flag. So

    poddb -d 30 -o popular tiny desk concert

will show the most popular Tiny Desk Concert episodes in the last month

Invoking Poddb with no query words will show you all the most recent
episodes from all the podcasts in the Poddb database. So to see the most
popular downloads in the last week, you can use

    poddb -d 7 -o popular

## Navigate podcast episodes

When you see a list of episodes, you can use the following key commands to
navigate, in addition to Vim's standard cursor commands:

* `l` or `ENTER` show episode detail
* `p` show all episodes for the podcast this item belongs to
* `CTRL-j` show next episode
* `CTRL-k` show previous episode
* `CTRL-o` and `CTRL-i` jump back and forward through screen history

If you press `p` to show all the episodes for the podcast, you can navigate back to the
previous screen with `CTRL-o` and return forward again with `CTRL-i`. In other words,
feel free to use Vim's jump-list navigation commands.

When you press `l` or `ENTER`, more information about the episode will appear in a split
window below the list.

## Download podcast episodes

* `d` mark episode for download; works with Vim selection ranges too
* `D` start downloading episode immediately and play with media player

If you mark episodes for downloading, Poddb will place a `*` in their left
margin and download them as soon as you quit the Vim interface with `:qa` or
some similar command.

Poddb uses `wget` to download episodes. The current version downloads all
marked episodes serially. A future version may implement parallel downloading.

Poddb downloads episodes into the current directory and saves them with
filenames that follow the format,

    {title of podcast}.{title of episode}.{poddb internal identifier}.{filetype extension}

Examples:

    Philosophy-Bites.Michael-Sandel-on-Justice.poddb_711_56523.mp3
    NPR-Tiny-Desk-Concerts-Podcast.Diego-Garcia.poddb_312_48461.m4v
    APM-Marketplace.09-14-11-Marketplace.poddb_16_55726.mp3

If you press `D`, Poddb will quit the Vim interface immediately and begin
downloading the episode that was under the cursor. After the download is
complete, Poddb will automatically start playing the episode with `mplayer` if
mplayer is available, and if not, the `open` command, which will play a media
file with iTunes on OS X.

You can force Poddb to launch a specific media player by setting the
`PODDB_MEDIA_PLAYER` environment variable and exporting it. For example, to
make Poddb use `totem`:

    export PODDB_MEDIA_PLAYER=totem
    poddb

Put the `export` command in your `.bash_profile` if you don't want to keep
typing it.

If you see a `D` on the left margin of an episode while you're looking at a
list of episodes, that means that you've already downloaded that episode into
the current directory.

## Favorite podcasts

When viewing a list of podcasts returned by `poddb -l`, you can add a podcast
to your favorites by putting the cursor over it and pressing `f`. Press `f`
again to remove the podcast from your favorite podcasts.  Favorite podcasts
have a `@` sign in the left margin.

    @ NPR Programs: Fresh Air from WHYY                            |     16 |      0 |  Sep 15 2011 |
      NPR Programs: Talk of the Nation                             |     41 |      0 |  Sep 15 2011 |
    @ NPR Programs: Tell Me More Podcast                           |     20 |      0 |  Sep 15 2011 |
      NPR Programs: Wait Wait... Don't Tell Me! Podcast            |     10 |      0 |  Sep 10 2011 |
      NPR Series: Alt.Latino Podcast                               |     21 |      0 |  Sep 14 2011 |
      NPR Series: From Scratch                                     |     16 |      0 |  Sep 14 2011 |
      NPR Series: Talk of the Nation Opinion Page Podcast          |     10 |      0 |  Sep 05 2011 |
      NPR Series: World Cafe: Next from WXPN Podcast               |     10 |      0 |  Sep 12 2011 |
      NPR Topics: Business Story of the Day Podcast                |     21 |      0 |  Sep 16 2011 |
      NPR Topics: Economy Podcast                                  |     11 |      0 |  Sep 13 2011 |
      NPR Topics: Education Podcast                                |     12 |      0 |  Sep 15 2011 |
      NPR Topics: Environment Podcast                              |     11 |      0 |  Sep 15 2011 |
    @ NPR Topics: Food Podcast                                     |     11 |      0 |  Sep 15 2011 |

Once you have a few favorite podcasts, you can list and navigate them with
the command

    poddb -F

You can also aggregate all the most recent episodes from your favorite episodes by
launching Poddb with the command

    poddb -f

Your favorite podcasts are stored in `~/.poddb/favorites` as a simple list of
podcast ids. The ids are internal to Poddb's PostgreSQL database.

## Bug reports and feature requests

Please submit them here:

* <https://github.com/danchoi/poddb_client/issues>

## About the app

Poddb has two parts, a client and a server. The client is a hybrid
Ruby/VimScript program packaged as a Ruby gem. The server is a Ruby
[Sinatra][sinatra] app sitting in front of a [PostgreSQL][postgres] database.
I use the [Sequel][sequel] database toolkit to interface between Ruby and SQL.
Podcast feeds are fetched with [curb][curb] and parsed with
[nokogiri][nokogiri].

[sinatra]:http://www.sinatrarb.com/
[postgres]:http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=postgresql
[sequel]:http://sequel.rubyforge.org/
[curb]:http://curb.rubyforge.org/
[nokogiri]:http://nokogiri.org/

## About the developer

My name is Daniel Choi. I make software with Ruby, Rails, MySQL, PostgreSQL,
and iOS. I am based in Cambridge, Massachusetts, USA, and the little software
company I run with Hoony Youn is called [Kaja
Software](http://kajasoftware.com).

* Company Email: info@kajasoftware.com
* Twitter: [@danchoi][twitter]
* Personal Email: dhchoi@gmail.com
* My Homepage: <http://danielchoi.com/software>

[twitter]:http://twitter.com/#!/danchoi


text:
package com.google.errorprone.refaster.testdata;

import com.google.common.io.ByteStreams;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Test data for {@code BlockPlaceholderTemplate}.
 */
public class BlockPlaceholderTemplateExample {
  public void positiveExample1() throws IOException {
    InputStream stream = new FileInputStream("foo.bar");
    try {
      System.out.println(ByteStreams.toByteArray(stream).length);
    } finally {
      stream.close();
    }
  }

  public void positiveExample2() throws IOException {
    InputStream stream = new FileInputStream("foo.bar");
    try {
      int count = 0;
      while (true) {
        int b = stream.read();
        if (b == -1) {
          break;
        }
        count++;
      }
      System.out.println(count);
    } finally {
      stream.close();
    }
  }

  public void negativeExample1() throws IOException { // modifies placeholder parameter
    InputStream stream = null;
    try {
      stream = new FileInputStream("foo.bar");
      System.out.println(ByteStreams.toByteArray(stream).length);
    } finally {
      stream.close();
    }
  }

  public void negativeExample2() throws IOException { // changes control flow
    for (int i = 0; i < 10; i++) {
      InputStream stream = new FileInputStream("foo.bar");
      try {
        System.out.println(ByteStreams.toByteArray(stream).length);
        break;
      } finally {
        stream.close();
      }
    }
  }
}


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <txdb.h>

#include <pow.h>
#include <random.h>
#include <shutdown.h>
#include <ui_interface.h>
#include <uint256.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/vector.h>

#include <validation.h>

#include <stdint.h>

#include <boost/thread.hpp>

static const char DB_COIN = 'C';
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_BLOCK_INDEX = 'b';

static const char DB_BEST_BLOCK = 'B';
static const char DB_HEAD_BLOCKS = 'H';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';

static const char DB_ADDRESSINDEX = 'a';
static const char DB_ADDRESSUNSPENTINDEX = 'u';
static const char DB_TIMESTAMPINDEX = 'S';
static const char DB_BLOCKHASHINDEX = 'z';
static const char DB_SPENTINDEX = 'p';

namespace {

struct CoinEntry {
    COutPoint* outpoint;
    char key;
    explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN)  {}

    template<typename Stream>
    void Serialize(Stream &s) const {
        s << key;
        s << outpoint->hash;
        s << VARINT(outpoint->n);
    }

    template<typename Stream>
    void Unserialize(Stream& s) {
        s >> key;
        s >> outpoint->hash;
        s >> VARINT(outpoint->n);
    }
};

}

CCoinsViewDB::CCoinsViewDB(fs::path ldb_path, size_t nCacheSize, bool fMemory, bool fWipe) : db(ldb_path, nCacheSize, fMemory, fWipe, true)
{
}

bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {
    return db.Read(CoinEntry(&outpoint), coin);
}

bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {
    return db.Exists(CoinEntry(&outpoint));
}

uint256 CCoinsViewDB::GetBestBlock() const {
    uint256 hashBestChain;
    if (!db.Read(DB_BEST_BLOCK, hashBestChain))
        return uint256();
    return hashBestChain;
}

std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const {
    std::vector<uint256> vhashHeadBlocks;
    if (!db.Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) {
        return std::vector<uint256>();
    }
    return vhashHeadBlocks;
}

bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
    CDBBatch batch(db);
    size_t count = 0;
    size_t changed = 0;
    size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
    int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
    assert(!hashBlock.IsNull());

    uint256 old_tip = GetBestBlock();
    if (old_tip.IsNull()) {
        // We may be in the middle of replaying.
        std::vector<uint256> old_heads = GetHeadBlocks();
        if (old_heads.size() == 2) {
            assert(old_heads[0] == hashBlock);
            old_tip = old_heads[1];
        }
    }

    // In the first batch, mark the database as being in the middle of a
    // transition from old_tip to hashBlock.
    // A vector is used for future extensibility, as we may want to support
    // interrupting after partial writes from multiple independent reorgs.
    batch.Erase(DB_BEST_BLOCK);
    batch.Write(DB_HEAD_BLOCKS, Vector(hashBlock, old_tip));

    for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
        if (it->second.flags & CCoinsCacheEntry::DIRTY) {
            CoinEntry entry(&it->first);
            if (it->second.coin.IsSpent())
                batch.Erase(entry);
            else
                batch.Write(entry, it->second.coin);
            changed++;
        }
        count++;
        CCoinsMap::iterator itOld = it++;
        mapCoins.erase(itOld);
        if (batch.SizeEstimate() > batch_size) {
            LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
            db.WriteBatch(batch);
            batch.Clear();
            if (crash_simulate) {
                static FastRandomContext rng;
                if (rng.randrange(crash_simulate) == 0) {
                    LogPrintf("Simulating a crash. Goodbye.\n");
                    _Exit(0);
                }
            }
        }
    }

    // In the last batch, mark the database as consistent with hashBlock again.
    batch.Erase(DB_HEAD_BLOCKS);
    batch.Write(DB_BEST_BLOCK, hashBlock);

    LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
    bool ret = db.WriteBatch(batch);
    LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
    return ret;
}

size_t CCoinsViewDB::EstimateSize() const
{
    return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));
}

CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
}

bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
    if (fReindexing)
        return Write(DB_REINDEX_FLAG, '1');
    else
        return Erase(DB_REINDEX_FLAG);
}

void CBlockTreeDB::ReadReindexing(bool &fReindexing) {
    fReindexing = Exists(DB_REINDEX_FLAG);
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read(DB_LAST_BLOCK, nFile);
}

CCoinsViewCursor *CCoinsViewDB::Cursor() const
{
    CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper&>(db).NewIterator(), GetBestBlock());
    /* It seems that there are no "const iterators" for LevelDB.  Since we
       only need read operations on it, use a const-cast to get around
       that restriction.  */
    i->pcursor->Seek(DB_COIN);
    // Cache key of first record
    if (i->pcursor->Valid()) {
        CoinEntry entry(&i->keyTmp.second);
        i->pcursor->GetKey(entry);
        i->keyTmp.first = entry.key;
    } else {
        i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false
    }
    return i;
}

bool CCoinsViewDBCursor::GetKey(COutPoint &key) const
{
    // Return cached key
    if (keyTmp.first == DB_COIN) {
        key = keyTmp.second;
        return true;
    }
    return false;
}

bool CCoinsViewDBCursor::GetValue(Coin &coin) const
{
    return pcursor->GetValue(coin);
}

unsigned int CCoinsViewDBCursor::GetValueSize() const
{
    return pcursor->GetValueSize();
}

bool CCoinsViewDBCursor::Valid() const
{
    return keyTmp.first == DB_COIN;
}

void CCoinsViewDBCursor::Next()
{
    pcursor->Next();
    CoinEntry entry(&keyTmp.second);
    if (!pcursor->Valid() || !pcursor->GetKey(entry)) {
        keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
    } else {
        keyTmp.first = entry.key;
    }
}

bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
        batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second);
    }
    batch.Write(DB_LAST_BLOCK, nLastFile);
    for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
        batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
    }
    return WriteBatch(batch, true);
}

bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
    return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}

bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
    char ch;
    if (!Read(std::make_pair(DB_FLAG, name), ch))
        return false;
    fValue = ch == '1';
    return true;
}

bool CBlockTreeDB::WriteAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Write(std::make_pair(DB_ADDRESSINDEX, it->first), it->second);
    return WriteBatch(batch);
}

bool CBlockTreeDB::EraseAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Erase(std::make_pair(DB_ADDRESSINDEX, it->first));
    return WriteBatch(batch);
}

bool CBlockTreeDB::ReadAddressIndex(uint256 addressHash, int type,
                                    std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
                                    int start, int end) {

    std::unique_ptr<CDBIterator> pcursor(NewIterator());

    if (start > 0 && end > 0) {
        pcursor->Seek(std::make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorHeightKey(type, addressHash, start)));
    } else {
        pcursor->Seek(std::make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorKey(type, addressHash)));
    }

    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char,CAddressIndexKey> key;
        if (pcursor->GetKey(key) && key.first == DB_ADDRESSINDEX && key.second.hashBytes == addressHash) {
            if (end > 0 && key.second.blockHeight > end) {
                break;
            }
            CAmount nValue;
            if (pcursor->GetValue(nValue)) {
                addressIndex.push_back(std::make_pair(key.second, nValue));
                pcursor->Next();
            } else {
                return error("failed to get address index value");
            }
        } else {
            break;
        }
    }

    return true;
}

bool CBlockTreeDB::UpdateAddressUnspentIndex(const std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue > >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=vect.begin(); it!=vect.end(); it++) {
        if (it->second.IsNull()) {
            batch.Erase(std::make_pair(DB_ADDRESSUNSPENTINDEX, it->first));
        } else {
            batch.Write(std::make_pair(DB_ADDRESSUNSPENTINDEX, it->first), it->second);
        }
    }
    return WriteBatch(batch);
}

bool CBlockTreeDB::ReadAddressUnspentIndex(uint256 addressHash, int type,
                                           std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs) {

    std::unique_ptr<CDBIterator> pcursor(NewIterator());
    pcursor->Seek(std::make_pair(DB_ADDRESSUNSPENTINDEX, CAddressIndexIteratorKey(type, addressHash)));

    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char,CAddressUnspentKey> key;
        if (pcursor->GetKey(key) && key.first == DB_ADDRESSUNSPENTINDEX && key.second.hashBytes == addressHash) {
            CAddressUnspentValue nValue;
            if (pcursor->GetValue(nValue)) {
                unspentOutputs.push_back(std::make_pair(key.second, nValue));
                pcursor->Next();
            } else {
                return error("failed to get address unspent value");
            }
        } else {
            break;
        }
    }

    return true;
}

bool CBlockTreeDB::WriteTimestampIndex(const CTimestampIndexKey &timestampIndex) {
    CDBBatch batch(*this);
    batch.Write(std::make_pair(DB_TIMESTAMPINDEX, timestampIndex), 0);
    return WriteBatch(batch);
}

bool CBlockTreeDB::ReadTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector<std::pair<uint256, unsigned int> > &hashes) {

    std::unique_ptr<CDBIterator> pcursor(NewIterator());

    pcursor->Seek(std::make_pair(DB_TIMESTAMPINDEX, CTimestampIndexIteratorKey(low)));

    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char, CTimestampIndexKey> key;
        if (pcursor->GetKey(key) && key.first == DB_TIMESTAMPINDEX && key.second.timestamp < high) {
            if (fActiveOnly) {
                if (blockOnchainActive(key.second.blockHash)) {
                    hashes.push_back(std::make_pair(key.second.blockHash, key.second.timestamp));
                }
            } else {
                hashes.push_back(std::make_pair(key.second.blockHash, key.second.timestamp));
            }

            pcursor->Next();
        } else {
            break;
        }
    }

    return true;
}

bool CBlockTreeDB::WriteTimestampBlockIndex(const CTimestampBlockIndexKey &blockhashIndex, const CTimestampBlockIndexValue &logicalts) {
    CDBBatch batch(*this);
    batch.Write(std::make_pair(DB_BLOCKHASHINDEX, blockhashIndex), logicalts);
    return WriteBatch(batch);
}

bool CBlockTreeDB::ReadTimestampBlockIndex(const uint256 &hash, unsigned int &ltimestamp) {

    CTimestampBlockIndexValue(lts);
    if (!Read(std::make_pair(DB_BLOCKHASHINDEX, hash), lts))
       return false;

    ltimestamp = lts.ltimestamp;
    return true;
}

bool CBlockTreeDB::ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) {
    return Read(std::make_pair(DB_SPENTINDEX, key), value);
}

bool CBlockTreeDB::UpdateSpentIndex(const std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<CSpentIndexKey,CSpentIndexValue> >::const_iterator it=vect.begin(); it!=vect.end(); it++) {
        if (it->second.IsNull()) {
            batch.Erase(std::make_pair(DB_SPENTINDEX, it->first));
        } else {
            batch.Write(std::make_pair(DB_SPENTINDEX, it->first), it->second);
        }
    }
    return WriteBatch(batch);
}

bool CBlockTreeDB::blockOnchainActive(const uint256 &hash) {
    LOCK(cs_main);
    BlockMap::iterator bit = ::BlockIndex().find(hash);

    if (bit != ::BlockIndex().end()) {
        if (::ChainActive().Contains(bit->second)) {
           return true;
        }
    }

    return false;
}

bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex)
{
    std::unique_ptr<CDBIterator> pcursor(NewIterator());

    pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));

    // Load m_block_index
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        if (ShutdownRequested()) return false;
        std::pair<char, uint256> key;
        if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
            CDiskBlockIndex diskindex;
            if (pcursor->GetValue(diskindex)) {
                // Construct block index object
                CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
                pindexNew->pprev          = insertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;

                if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams))
                    return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString());

                pcursor->Next();
            } else {
                return error("%s: failed to read value", __func__);
            }
        } else {
            break;
        }
    }

    return true;
}

namespace {

//! Legacy class to deserialize pre-pertxout database entries without reindex.
class CCoins
{
public:
    //! whether transaction is a coinbase
    bool fCoinBase;

    //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
    std::vector<CTxOut> vout;

    //! at which height this transaction was included in the active block chain
    int nHeight;

    //! empty constructor
    CCoins() : fCoinBase(false), vout(0), nHeight(0) { }

    template<typename Stream>
    void Unserialize(Stream &s) {
        unsigned int nCode = 0;
        // version
        unsigned int nVersionDummy;
        ::Unserialize(s, VARINT(nVersionDummy));
        // header code
        ::Unserialize(s, VARINT(nCode));
        fCoinBase = nCode & 1;
        std::vector<bool> vAvail(2, false);
        vAvail[0] = (nCode & 2) != 0;
        vAvail[1] = (nCode & 4) != 0;
        unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
        // spentness bitmask
        while (nMaskCode > 0) {
            unsigned char chAvail = 0;
            ::Unserialize(s, chAvail);
            for (unsigned int p = 0; p < 8; p++) {
                bool f = (chAvail & (1 << p)) != 0;
                vAvail.push_back(f);
            }
            if (chAvail != 0)
                nMaskCode--;
        }
        // txouts themself
        vout.assign(vAvail.size(), CTxOut());
        for (unsigned int i = 0; i < vAvail.size(); i++) {
            if (vAvail[i])
                ::Unserialize(s, Using<TxOutCompression>(vout[i]));
        }
        // coinbase height
        ::Unserialize(s, VARINT_MODE(nHeight, VarIntMode::NONNEGATIVE_SIGNED));
    }
};

}

/** Upgrade the database from older formats.
 *
 * Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout.
 */
bool CCoinsViewDB::Upgrade() {
    std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
    pcursor->Seek(std::make_pair(DB_COINS, uint256()));
    if (!pcursor->Valid()) {
        return true;
    }

    int64_t count = 0;
    LogPrintf("Upgrading utxo-set database...\n");
    LogPrintf("[0%%]..."); /* Continued */
    uiInterface.ShowProgress(_("Upgrading UTXO database").translated, 0, true);
    size_t batch_size = 1 << 24;
    CDBBatch batch(db);
    int reportDone = 0;
    std::pair<unsigned char, uint256> key;
    std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()};
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        if (ShutdownRequested()) {
            break;
        }
        if (pcursor->GetKey(key) && key.first == DB_COINS) {
            if (count++ % 256 == 0) {
                uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1);
                int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5);
                uiInterface.ShowProgress(_("Upgrading UTXO database").translated, percentageDone, true);
                if (reportDone < percentageDone/10) {
                    // report max. every 10% step
                    LogPrintf("[%d%%]...", percentageDone); /* Continued */
                    reportDone = percentageDone/10;
                }
            }
            CCoins old_coins;
            if (!pcursor->GetValue(old_coins)) {
                return error("%s: cannot parse CCoins record", __func__);
            }
            COutPoint outpoint(key.second, 0);
            for (size_t i = 0; i < old_coins.vout.size(); ++i) {
                if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {
                    Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);
                    outpoint.n = i;
                    CoinEntry entry(&outpoint);
                    batch.Write(entry, newcoin);
                }
            }
            batch.Erase(key);
            if (batch.SizeEstimate() > batch_size) {
                db.WriteBatch(batch);
                batch.Clear();
                db.CompactRange(prev_key, key);
                prev_key = key;
            }
            pcursor->Next();
        } else {
            break;
        }
    }
    db.WriteBatch(batch);
    db.CompactRange({DB_COINS, uint256()}, key);
    uiInterface.ShowProgress("", 100, false);
    LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE");
    return !ShutdownRequested();
}


text:
import { KeyHandler } from './KeyHandler';

/**
 * This module integrates {@link E2EEContext} with {external} in order to set the keys for encryption.
 */
export class ExternallyManagedKeyHandler extends KeyHandler {
    /**
     * Build a new ExternallyManagedKeyHandler instance, which will be used in a given conference.
     * @param conference - the current conference.
     */
    constructor(conference) {
        super(conference, { sharedKey: true });
    }

    /**
     * Sets the key and index for End-to-End encryption.
     *
     * @param {CryptoKey} [keyInfo.encryptionKey] - encryption key.
     * @param {Number} [keyInfo.index] - the index of the encryption key.
     * @returns {void}
     */
    setKey(keyInfo) {
        this.e2eeCtx.setKey(undefined, { encryptionKey: keyInfo.encryptionKey }, keyInfo.index);
    }
}


text:
const merge = require('webpack-merge');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const sharedConfig = require('./shared.js');

const rootPath = path.resolve(process.cwd());

module.exports = merge(sharedConfig, {
  mode: 'production',
  output: { filename: '[name].[chunkhash].js' },
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            query: {
              mozjpeg: { progressive: true },
              gifsicle: { interlaced: false },
              optipng: { optimizationLevel: 7 },
              pngquant: { quality: '75-90', speed: 4 },
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: [ { loader: MiniCssExtractPlugin.loader }, 'css-loader' ],
      },
      {
        test: /\.(scss|sass)$/,
        use: [
          { loader: MiniCssExtractPlugin.loader },
          {
            loader: 'css-loader',
            options: { sourceMap: true, importLoaders: 1 },
          },
          { loader: 'postcss-loader', options: { sourceMap: true } },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
              includePaths: [ path.resolve(rootPath, './app/styles') ],
            },
          },
        ],
      },
    ],
  },
  optimization: {
    concatenateModules: true,
    minimize: true,
    minimizer: [
      new TerserPlugin(),
      new OptimizeCSSAssetsPlugin({}),
    ],
    runtimeChunk: true,
    splitChunks: { chunks: 'all' },
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[name].[contenthash].[id].css',
    }),
    new ManifestPlugin(),
  ],
  externals: { leaflet: 'L', 'esri-leaflet': 'L.esri' },
});


text:
CREATE TYPE SUBSCRIBERS_STATUS AS ENUM (
  'CREATED',  -- registered but not verified, logins should not be possible
  'ACTIVE',   -- verified and can actively login
  'RESET',    -- password reset, no logins possible only pwd reset procedure
  'CLOSED'    -- closed, no functionality is supported against this state
);

-- create the primary subscriber table
CREATE TABLE subscriber
(
  id SERIAL PRIMARY KEY,                       -- internal id uses for sub
  email VARCHAR(128) NOT NULL UNIQUE,          -- email owned by sub
  password VARCHAR(60) NOT NULL,               -- hashed pwd of sub
  reg_date TIMESTAMP WITH TIME ZONE NOT NULL,  -- date/time of registration
  reg_ip INET NOT NULL,                        -- ip used for registration
  verification_token CHAR(36) NOT NULL UNIQUE, -- verification token
  status SUBSCRIBERS_STATUS NOT NULL           -- current sub disposition
);

CREATE TYPE MAILER_STATUS AS ENUM (
  'SUBSCRIBED',
  'UNSUBSCRIBE'
);

CREATE TABLE flogmailer
(
  id SERIAL PRIMARY KEY , -- internal mailer id
  firstname varchar(30) NOT NULL,
  lastname varchar(30) NOT NULL,
  company varchar(60),
  email varchar(128) NOT NULL,
  subscribe_token CHAR(36) NOT NULL UNIQUE,
  status MAILER_STATUS NOT NULL
);

-- create a session table
CREATE TABLE session
(
  id SERIAL PRIMARY KEY,                            -- internal sesison id
  subscriber_id INTEGER references subscriber(id) NOT NULL, -- reference to sub
  key CHAR(36) NOT NULL UNIQUE,                     -- session key for API
  timeout TIMESTAMP WITH TIME ZONE NOT NULL         -- date/time for session to end
  -- ip INET NOT NULL                               -- ip used for session
);

-- create the primary packet table
CREATE TABLE packet
(
  id SERIAL PRIMARY KEY,                         -- internal id uses for sub
  subscriber_id INTEGER references subscriber(id) NOT NULL, -- reference to sub
  name VARCHAR(60) NOT NULL,                                -- packet name
  packet JSON NOT NULL,                                     -- packet
  unique(subscriber_id, name)                             -- name unique to sub
);

-- create the primary profile table
CREATE TABLE profile
(
  id SERIAL PRIMARY KEY,                        -- internal id uses for sub
  subscriber_id INTEGER references subscriber(id) NOT NULL, -- ref to sub
  name VARCHAR(60) NOT NULL,                                -- profile name
  profile JSON NOT NULL,                                    -- profile
  unique(subscriber_id, name)                              -- name unique to sub
);

-- create the primary switch table
CREATE TABLE switch
(
  id SERIAL PRIMARY KEY,                        -- internal id uses for sub
  subscriber_id INTEGER references subscriber(id) NOT NULL, -- ref to sub
  name VARCHAR(60) NOT NULL,                                -- switch name
  _switch JSON NOT NULL,                                    -- switch
  unique(subscriber_id, name)                              -- name unique to sub
);

-- create the primary trace table
CREATE TABLE trace
(
  id SERIAL PRIMARY KEY,                        -- internal id uses for sub
  subscriber_id INTEGER references subscriber(id) NOT NULL, -- ref to sub
  name VARCHAR(60) NOT NULL,                                -- trace name
  trace JSON NOT NULL,                                    -- trace
  unique(subscriber_id, name)                              -- name unique to sub
);