text:
class WXDLLIMPEXP_FWD_CORE wxTextCtrl;
class WXDLLIMPEXP_FWD_CORE wxLogFrame;
class WXDLLIMPEXP_FWD_CORE wxWindow;
// ----------------------------------------------------------------------------
// the following log targets are only compiled in if the we're compiling the
// GUI part (andnot just the base one) of the library, they're implemented in
// src/generic/logg.cpp *and not src/common/log.cpp unlike all the rest)
// ----------------------------------------------------------------------------

#if wxUSE_TEXTCTRL

// log everything to a text window (GUI only of course)
class WXDLLIMPEXP_CORE wxLogTextCtrl : public wxLog
{
public:
  wxLogTextCtrl(wxTextCtrl* pTextCtrl);
protected:
    // implement sink function
  void DoLogText(const wxString& msg) override;
private:
    // the control we use
  wxTextCtrl* m_pTextCtrl;
  wxDECLARE_NO_COPY_CLASS(wxLogTextCtrl);
};
// ----------------------------------------------------------------------------
// GUI log target, the default one for wxWidgets programs
// ----------------------------------------------------------------------------
#    if  wxUSE_LOGGUI
class WXDLLIMPEXP_CORE wxLogGui : public wxLog
{
public:
    // ctor
  wxLogGui();
    // show all messages that were logged since the last Flush()
  void Flush() override;
protected:
  void DoLogRecord(wxLogLevel level, const wxString& msg, const wxLogRecordInfo& info) override;
    // return the title to be used for the log dialog, depending on m_bErrors
    // and m_bWarnings values
  wxString GetTitle() const;
    // return the icon (one of wxICON_XXX constants) to be used for the dialog
    // depending on m_bErrors/m_bWarnings
  int GetSeverityIcon() const;
    // empty everything
  void Clear();
  wxArrayString m_aMessages;
  wxArrayInt m_aSeverity;
  wxArrayLong m_aTimes;
  bool m_bErrors, m_bWarnings, m_bHasMessages;
private:
    // this method is called to show a single log message, it uses
    // wxMessageBox() by default
  virtual void DoShowSingleLogMessage(const wxString& message, const wxString& title, int style);
    // this method is called to show multiple log messages, it uses wxLogDialog
  virtual void DoShowMultipleLogMessages(const wxArrayString& messages, const wxArrayInt& severities, const wxArrayLong& times, const wxString& title, int style);
};
#    endif
// ----------------------------------------------------------------------------
// (background) log window: this class forwards all log messages to the log
// target which was active when it was instantiated, but also collects them
// to the log window. This window has its own menu which allows the user to
// close it, clear the log contents or save it to the file.
// ----------------------------------------------------------------------------
#    if  wxUSE_LOGWINDOW
class WXDLLIMPEXP_CORE wxLogWindow : public wxLogPassThrough
{
public:
  wxLogWindow(wxWindow* pParent, const wxString& szTitle, bool bShow = true, bool bPassToOld = true);
  virtual ~wxLogWindow();
    // window operations
        // show/hide the log window
  void Show(bool bShow = true);
        // retrieve the pointer to the frame
  wxFrame* GetFrame() const;
    // overridables
        // called if the user closes the window interactively, will not be
        // called if it is destroyed for another reason (such as when program
        // exits) - return true from here to allow the frame to close, false
        // to prevent this from happening
  virtual bool OnFrameClose(wxFrame* frame);
        // called right before the log frame is going to be deleted: will
        // always be called unlike OnFrameClose()
  virtual void OnFrameDelete(wxFrame* frame);
protected:
  void DoLogTextAtLevel(wxLogLevel level, const wxString& msg) override;
private:
  wxLogFrame* m_pLogFrame;
  wxDECLARE_NO_COPY_CLASS(wxLogWindow);
};
#    endif
#  endif
#endif


text:
//   Copyright 2003-2019 Romain Boman
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#ifndef GMMESH_H
#define GMMESH_H

#include "genmai.h"
#include "gmObject.h"
#include <vector>

namespace genmai
{

/**
 * @brief Defines a Mesh (list of Point and list of Element).
 *        A list of contact nodes is also included.
 */

class GENMAI_API Mesh : public Object
{
public:
    int firstContactNode;
    int lastContactNode;

    std::vector<Point *> nodes;
    std::vector<Element *> elements;

public:
    Mesh();

    virtual void write(std::ostream &out) const override;
    virtual void list() const;

    bool isEmpty() const;
    void clear();
};

} // namespace genmai

#endif // GMMESH_H

redpajama_set_name: RedPajamaGithub


text:
let isDone: boolean = false;
// or
const truth: boolean = true;

// number literals
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

// string
let color: string = 'blue';
// interpolation
let sentence: string = `My favorite color is ${color}`;

// list
let list: Array<number> = [1, 2, 3];

// tuples (seems dumb)
let myTuple: [string, number];
// Initialize it
myTuple = ["hello", 10]; // OK
// Initialize it incorrectly
myTuple = [10, "hello"]; // Error

// enum
enum Color { Red, Green, Blue }
let c: Color = Color.Green;
// Really just ints starting at 0
enum Direction { Up = 3, Down = 5, Left = 8, Right = 13 }
console.log(Direction[5]) // Prints the string 'Down'

// void is the abscence of a type
function warnUser(): void {
  console.log("This is my warning message");
}
// never is bottom
function boom(message: string): never {
  throw new Error(message);
}

// undefined and null are also types
let u: undefined = undefined;
let n: null = null;

// object is a type that represents the non-primitive type
// i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined.
let o: object = { foo: "bar" };

// there's also an escape hatch
let someValue: any = "don't do this";

// type assertions/casts
let strLength1: number = (<string>someValue).length;
// same as
let strLength2: number = (someValue as string).length;

// Note that String and string are not equivalent, same with
// Number, Boolean, Symbol, and Object

/// Variable Declaration

// always prefer const
const x: number = 5;

// array destructuring
let arr1: Array<string> = ["foo", "bar"];
let [f, g] = arr1;

// object destructuring
let obj: object = { a: 300, b: "sparta" }
let { a, b } = obj;
// with renaming
let { c: count, d: polis } = obj;
console.log(`We ${count} of ${polis}`)

// spread
let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];

let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };

// Check this out!
let arr2: ReadonlyArray<number> = [1, 2, 3];

/// Interfaces

// There are two ways to declare types: interface and type
// Prefer interface unless you need the features of type

// An interface is just the shape of data
interface MyInterface {
  label: string;
  optional?: number;
  readonly awesome: boolean;
}
function printLabel(obj: MyInterface) {
  console.log(obj.label);
}
let myObj = { size: 10, label: "Size 10 Object", awesome: true }
printLabel(myObj);

/// Functions

interface MultipleOf {
  (a: number, b: number): boolean;
}

let multipleOf: MultipleOf;

// Note that the param names don't have to match
multipleOf = function(x: number, y: number): boolean {
  return x % y === 0;
};

/// Types

// Unions
type WindowStates = "open" | "closed" | "minimized";


text:
namespace ui {

DrmGpuPlatformSupportHost::DrmGpuPlatformSupportHost(DrmCursor* cursor)
    : host_id_(-1), cursor_(cursor) {
}

DrmGpuPlatformSupportHost::~DrmGpuPlatformSupportHost() {
}

void DrmGpuPlatformSupportHost::RegisterHandler(
    GpuPlatformSupportHost* handler) {
  handlers_.push_back(handler);

  if (IsConnected())
    handler->OnChannelEstablished(host_id_, send_runner_, send_callback_);
}

void DrmGpuPlatformSupportHost::UnregisterHandler(
    GpuPlatformSupportHost* handler) {
  std::vector<GpuPlatformSupportHost*>::iterator it =
      std::find(handlers_.begin(), handlers_.end(), handler);
  if (it != handlers_.end())
    handlers_.erase(it);
}

void DrmGpuPlatformSupportHost::AddChannelObserver(ChannelObserver* observer) {
  channel_observers_.AddObserver(observer);

  if (IsConnected())
    observer->OnChannelEstablished();
}

void DrmGpuPlatformSupportHost::RemoveChannelObserver(
    ChannelObserver* observer) {
  channel_observers_.RemoveObserver(observer);
}

bool DrmGpuPlatformSupportHost::IsConnected() {
  return host_id_ >= 0;
}

void DrmGpuPlatformSupportHost::OnChannelEstablished(
    int host_id,
    scoped_refptr<base::SingleThreadTaskRunner> send_runner,
    const base::Callback<void(IPC::Message*)>& send_callback) {
  TRACE_EVENT1("drm", "DrmGpuPlatformSupportHost::OnChannelEstablished",
               "host_id", host_id);
  host_id_ = host_id;
  send_runner_ = send_runner;
  send_callback_ = send_callback;

  for (size_t i = 0; i < handlers_.size(); ++i)
    handlers_[i]->OnChannelEstablished(host_id, send_runner_, send_callback_);

  FOR_EACH_OBSERVER(ChannelObserver, channel_observers_,
                    OnChannelEstablished());

  // The cursor is special since it will process input events on the IO thread
  // and can by-pass the UI thread. This means that we need to special case it
  // and notify it after all other observers/handlers are notified such that the
  // (windowing) state on the GPU can be initialized before the cursor is
  // allowed to IPC messages (which are targeted to a specific window).
  cursor_->OnChannelEstablished(host_id, send_runner_, send_callback_);
}

void DrmGpuPlatformSupportHost::OnChannelDestroyed(int host_id) {
  TRACE_EVENT1("drm", "DrmGpuPlatformSupportHost::OnChannelDestroyed",
               "host_id", host_id);
  cursor_->OnChannelDestroyed(host_id);

  if (host_id_ == host_id) {
    host_id_ = -1;
    send_runner_ = nullptr;
    send_callback_.Reset();
    FOR_EACH_OBSERVER(ChannelObserver, channel_observers_,
                      OnChannelDestroyed());
  }

  for (size_t i = 0; i < handlers_.size(); ++i)
    handlers_[i]->OnChannelDestroyed(host_id);
}

bool DrmGpuPlatformSupportHost::OnMessageReceived(const IPC::Message& message) {
  for (size_t i = 0; i < handlers_.size(); ++i)
    if (handlers_[i]->OnMessageReceived(message))
      return true;

  return false;
}

bool DrmGpuPlatformSupportHost::Send(IPC::Message* message) {
  if (IsConnected() &&
      send_runner_->PostTask(FROM_HERE, base::Bind(send_callback_, message)))
    return true;

  delete message;
  return false;
}

}  // namespace ui


text:
package com.jongsoft.harvester.web;

import com.jongsoft.harvester.HarvesterApplication;
import com.jongsoft.harvester.entity.security.UserEntity;
import com.jongsoft.harvester.security.HarvesterSecurityService;
import com.jongsoft.harvester.service.OrganisationService;
import com.jongsoft.harvester.util.SecurityUtil;
import java.io.UnsupportedEncodingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin/users")
public class UserController {
    private static final String ACTION_REDIRECT_LIST = "redirect:/admin/users/";

    @Autowired private HarvesterSecurityService harvesterSecurityService;
    @Autowired private PasswordEncoder passwordEncoder;
    @Autowired private OrganisationService organisationService;

    @RequestMapping("/")
    public String index(Model model) {
        model.addAttribute("entities", harvesterSecurityService.searchByName(""));
        return "users/listing";
    }

    @RequestMapping("/{username}")
    public String show(Model model, @PathVariable("username") String encodedUsername, RedirectAttributes redirect)
            throws UnsupportedEncodingException {

        String username = SecurityUtil.decode(encodedUsername);
        UserEntity user = harvesterSecurityService.get(username);

        if (user == null) {
            redirect.addFlashAttribute(HarvesterApplication.GLOBAL_MESSAGE_ERROR, "entity.user.notfound");
            return ACTION_REDIRECT_LIST;
        }

        model.addAttribute(user);

        return "users/edit";
    }

    @RequestMapping(value = "/{username}", method = RequestMethod.POST)
    public String update(@PathVariable("username") String encodedUsername, UserEntity update, BindingResult result,
            @RequestParam(value = "passwordReset", defaultValue = "false") boolean passwordReset,
            RedirectAttributes redirect) throws UnsupportedEncodingException {

        UserEntity user = harvesterSecurityService.get(SecurityUtil.decode(encodedUsername));
        if (user == null) {
            redirect.addFlashAttribute(HarvesterApplication.GLOBAL_MESSAGE_ERROR, "entity.user.notfound");
            return ACTION_REDIRECT_LIST;
        }

        if (!result.hasErrors()) {
            if (passwordReset) {
                user.setPassword(passwordEncoder.encode(update.getPassword()));
            }
            user.setRoles(update.getRoles());
            harvesterSecurityService.update(user);

            redirect.addFlashAttribute(HarvesterApplication.GLOBAL_MESSAGE_SUCCESS, "entity.user.updated");
            return ACTION_REDIRECT_LIST;
        }

        return "users/edit";
    }

    @RequestMapping("/{username}/organisations")
    public String organisations(Model model, @PathVariable("username") String encodedUsername,
            RedirectAttributes redirect) throws UnsupportedEncodingException {
        String username = SecurityUtil.decode(encodedUsername);
        UserEntity user = harvesterSecurityService.get(username);

        if (user == null) {
            redirect.addFlashAttribute(HarvesterApplication.GLOBAL_MESSAGE_ERROR, "entity.user.notfound");
            return ACTION_REDIRECT_LIST;
        }

        model.addAttribute("manages", organisationService.getByOwner(username));
        model.addAttribute("user", user);
        return "users/user-organisations";
    }

}


text:
"""``dcrpd.py``

`Class to abstract dcrpd operations`

"""

from testlib.custom_exceptions import UICmdException
from testlib.linux import service_lib
from testlib.ui_onpss_shell.switch_driver import SwitchDriver

class Dcrpd(object):

    SERVICE = 'dcrpd'
    CONFIG_PATH = "/usr/lib/systemd/system/"
    MANIFEST_FILE = CONFIG_PATH + "dcrpd.service"

    def __init__(self, run_command, switch):
        """Initialize Dcrpd class.

        Args:
            run_command(function): function that runs the actual commands

        """
        super(Dcrpd, self).__init__()
        self.run_command = run_command
        self.switch = switch
        self.switch_driver = SwitchDriver(self, switch)
        self.service_manager = service_lib.SpecificServiceManager(self.SERVICE, self.run_command)

    def start(self):
        """Start dcrpd process.

        Raises:
            UICmdException: On non-zero return code

        """
        self.switch.ui.modify_ports(ports=[self.switch.ui.cpu_port], adminMode='Up')
        self.service_manager.start()

    def stop(self):
        """Stop dcrpd process.

        Raises:
            UICmdException: On non-zero return code

        """
        self.service_manager.stop()
        self.switch.ui.modify_ports(ports=[self.switch.ui.cpu_port], adminMode='Down')

    def restart(self):
        """Restarting dcrpd process.

        Raises:
            UICmdException: On non-zero return code

        """
        self.service_manager.restart()

    def force_reload(self):
        """Restarting the switch driver and then the dcrpd process.

        Raises:
            UICmdException: On non-zero return code

        """
        self.switch_driver.force_reload()
        self.switch.ui.modify_ports(ports=[self.switch.ui.cpu_port], adminMode='Up')
        self.restart()

    def enable(self):
        """Enabling dcrpd service on start.

        Raises:
            UICmdException: On non-zero return code

        """
        self.service_manager.enable()

    def disable(self):
        """Disabling dcrpd service on start.

        Raises:
            UICmdException: On non-zero return code

        """
        self.service_manager.disable()

    def get_status(self):
        """Get dcrpd process status.

        Raises:
            UICmdException: On non-zero or non-three return code

        Returns:
            str

        """
        try:
            result = self.service_manager.status()
        except UICmdException as err:
            if err.rc == 3:
                # If service is not active
                return err.stdout
            else:
                raise

        return result.stdout


text:
import networkx as nx
from api.apiutils import Relation

from modelstore.elasticstore import StoreHandler, KWType
from knowledgerepr import fieldnetwork
from algebra import API

path_to_serialized_model = "/Users/arcarter/code/datadiscovery/test/testmodel/"
network = fieldnetwork.deserialize_network(path_to_serialized_model)
store_client = StoreHandler()

api = API(network, store_client)

# short variables for Scope
# These are used in keyword searches
# To specify what parts of a file will be searched
source = KWType.KW_TABLE  # table/file/source name
field = KWType.KW_SCHEMA  # colum names/fields
content = KWType.KW_CONTENT  # content of the columns

# Short variables for Relation
# These represent edge types in the graph
# and are used for neighbor searches
# schema = Relation.SCHEMA  # similar schemas
schema_sim = Relation.SCHEMA_SIM  # Similar Schema Names
# similar content values. i.e. matching substrings and numbers
content_sim = Relation.CONTENT_SIM
# entity_sim = Relation.ENTITY_SIM  # similar column names
pkfk = Relation.PKFK  # join candidates

# Short variables for api
# These are algebraic functions that can be used to discover data
keyword_search = api.keyword_search
neighbor_search = api.neighbor_search
paths = api.paths
traverse = api.traverse
make_drs = api.make_drs

intersection = api.intersection
union = api.union
difference = api.difference

@DeprecationWarning
def search(kws, contexts=[source, field, content]):
    try:
        if isinstance(contexts, KWType):
            contexts = [contexts]
        drs = None
        if isinstance(kws, str):
            kws = [kws]
        if isinstance(contexts, str):
            raise Exception

        for kw in kws:
            for kwtype in contexts:
                new_drs = keyword_search(kw, kwtype, max_results=500)
                drs = union(drs, new_drs)
        return drs
    except Exception:
        msg = (
            '--- Error ---' +
            '\nThis function searches datasets for one or more keywords.'
            '\nusage:\n\tsearch( (string|[string, string])' +
            ' [, KWType | (KWTYpe, KWType, KWTYpe)] )' +
            '\ne.g.:\n\tsearch(\'school\')' +
            '\n\tsearch(\'school\', field)' +
            '\n\tsearch([\'school\', \'education\'])' +
            '\n\tsearch(\'school\', [source, field, content])')
        print(msg)

@DeprecationWarning
def neighbors(i_drs, relations=Relation, exclude_origin=True):
    try:
        i_drs = api.make_drs(i_drs)
        o_drs = None

        if relations is None:
            relations = [pkfk, content_sim, schema_sim]
        if isinstance(relations, Relation):
            relations = [relations]
        if isinstance(relations, KWType):
            raise ValueError(
                'relation must be schema_sim, content_ sim, pkfk' +
                'or an array of those values')

        for relation in relations:
            new_drs = neighbor_search(i_drs, relation)
            o_drs = union(o_drs, new_drs)

        if exclude_origin:
            o_drs = difference(o_drs, i_drs)

        return o_drs
    except:
        msg = (
            '--- Error ---' +
            '\nThis function searches for neighbors of domain result set ' +
            'or one of its precursors.' +
            '\nusage:\n\tneighbors( ' +
            '(drs/table name/hit id | [drs/hit/table_name/hit id, ' +
            'drs/hit/table_name/hit id])' +
            '\n\t\t[, Relation | (Relation, Relation, Relation)]' +
            '\n\t\t[,exclude_origin=True/False] )' +
            '\ne.g.:\n\tneighbors(\'Boston Capital Phase_pfp2-xvaj.csv\')' +
            '\n\tneighbors(1600820766, schema_sim)' +
            '\n\tneighbors([my_domain_result_set, [schema_sim, content_sim])' +
            '\n\tneighbors([1600820766, my_drs], exclude_origin=False)')
        print(msg)

@DeprecationWarning
def path(drs_a, drs_b, relation=pkfk):
    try:
        drs_a = make_drs(drs_a)
        drs_b = make_drs(drs_b)
        drs = api.paths(drs_a, drs_b, relation)
        return drs
    except:
        msg = (
            '--- Error ---' +
            '\nThis function returns a drs showing how to get between one ' +
            'drs and another, using a specified Relation.' +
            '\nusage:\n\tpath(drs_a, drs_b)' +
            '\ne.g.:\n\tdrs_a = search(\'school\')' +
            '\n\tdrs_b = search(\'occupation\')' +
            '\n\tpath(drs_a, drs_b, pkfk). ' +
            '\n\nIf you are trying to find paths internal to a DRS, use ' +
            '\n\tdrs.paths()'
        )
        print(msg)

@DeprecationWarning
def provenance(i_drs):
    try:
        return i_drs.get_provenance().prov_graph().edges()
    except:
        msg = (
            '--- Error ---' +
            '\nThis function returns a graph showing how a domain result set' +
            'was reached.'
            '\nusage:\n\tprovenance(drs)' +
            '\ne.g.:\n\tmy_drs = search(\'school\')' +
            '\n\tprovenance(my_drs)')
        print(msg)

if __name__ == '__sugar__':
    pass


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="colorPrimary">#bb8a48</color>
    <color name="colorPrimaryDark">#845f3b</color>
    <color name="colorAccent">#cd9945</color>
    <color name="colorAccentLight">#ffcc80</color>

    <color name="navDrawerBackground">#FAFAFA</color>

    <color name="fontCardColor">#FAFAFA</color>
    <color name="bitmapCardColor">#363636</color>
    <color name="svgCardColor">#E3E3E3</color>
    <color name="videoForegroundColor">#131313</color>

</resources>


text:
import {vsyncFor} from '../../../src/vsync';
import {viewportFor} from '../../../src/viewport';
import {setStyles} from '../../../src/style';

/** @type {string} */
const OBJ_PROP = '__BUBBLE_OBJ';

export class ValidationBubble {

  /**
   * Creates a bubble component to display messages in.
   * @param {!Window} win
   */
  constructor(win) {

    /** @private @const {!Viewport} */
    this.viewport_ = viewportFor(win);

    /** @private @const {!../../../src/service/vsync-impl.Vsync} */
    this.vsync_ = vsyncFor(win);

    /** @private @const {!HTMLDivElement} */
    this.bubbleElement_ = win.document.createElement('div');
    this.bubbleElement_.classList.add('-amp-validation-bubble');
    this.bubbleElement_[OBJ_PROP] = this;
    win.document.body.appendChild(this.bubbleElement_);
  }

  /**
   * Hides the bubble off screen.
   */
  hide() {
    // TODO(#3776): Use .mutate method when it supports passing state.
    this.vsync_.run({
      measure: undefined,
      mutate: hideBubble,
    }, {
      bubbleElement: this.bubbleElement_,
    });
  }

  /**
   * Shows the bubble targeted to an element with the passed message.
   * @param {!HTMLElement} targetElement
   * @param {string} message
   */
  show(targetElement, message) {
    const state = {
      message,
      targetElement,
      bubbleElement: this.bubbleElement_,
      viewport: this.viewport_,
    };
    this.vsync_.run({
      measure: measureTargetElement,
      mutate: showBubbleElement,
    }, state);
  }
}

/**
 * Hides the bubble element passed through state object.
 * @param {!Object} state
 * @private
 */
function hideBubble(state) {
  setStyles(state.bubbleElement, {
    display: 'none',
  });
}

/**
 * Measures the layout for the target element passed through state object.
 * @param {!Object} state
 * @private
 */
function measureTargetElement(state) {
  state.targetRect = state.viewport.getLayoutRect(state.targetElement);
}

/**
 * Updates text content, positions and displays the bubble.
 * @param {!Object} state
 * @private
 */
function showBubbleElement(state) {
  state.bubbleElement.textContent = state.message;
  setStyles(state.bubbleElement, {
    display: 'block',
    top: `${state.targetRect.top - 10}px`,
    left: `${state.targetRect.left + state.targetRect.width / 2}px`,
  });
}


text:
package org.kaaproject.kaa.demo.iotworld.smarthome.fragment.card;

import java.nio.ByteBuffer;

import org.kaaproject.kaa.demo.iotworld.music.AlbumInfo;
import org.kaaproject.kaa.demo.iotworld.music.PlaybackInfo;
import org.kaaproject.kaa.demo.iotworld.music.SongInfo;
import org.kaaproject.kaa.demo.iotworld.smarthome.R;
import org.kaaproject.kaa.demo.iotworld.smarthome.data.MusicDevice;
import org.kaaproject.kaa.demo.iotworld.smarthome.util.TimeUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MusicCard extends AbstractGeoFencingDeviceCard<MusicDevice> {

    private View mNoTrackSelectedView;
    private View mMusicDetailsView;

    private ImageView mAlbumCoverView;
    private TextView mAlbumTitleView;
    private TextView mArtistTitleView;
    private TextView mTrackTitleView;
    private Bitmap mAlbumCoverBitmap;
    private SeekBar mTrackProgressView;
    private TextView mTrackProgressTextView;

    public MusicCard(Context context) {
        super(context);
        mNoTrackSelectedView = findViewById(R.id.noTrackSelectedView);
        mMusicDetailsView = findViewById(R.id.musicDetailsView);

        mAlbumCoverView = (ImageView) findViewById(R.id.albumCoverView);
        mAlbumTitleView = (TextView) findViewById(R.id.albumTitleView);
        mArtistTitleView = (TextView) findViewById(R.id.artistTitleView);
        mTrackTitleView = (TextView) findViewById(R.id.trackTitleView);
        mTrackProgressView = (SeekBar) findViewById(R.id.trackProgressView);
        mTrackProgressTextView = (TextView) findViewById(R.id.trackProgressTextView);

        mTrackProgressView.setEnabled(false);

    }

    @Override
    protected int getCardLayout() {
        return R.layout.card_music_device;
    }

    @Override
    public void bind(MusicDevice device) {
        super.bind(device);
        PlaybackInfo playbackInfo = device.getPlaybackInfo();
        if (playbackInfo != null) {
            setDetailsVisible(true);
            SongInfo song = playbackInfo.getSong();
            AlbumInfo album = null;
            if (song != null) {
                album = device.getAlbum(song.getAlbumId());
            }
            if (song != null && album != null) {
                mNoTrackSelectedView.setVisibility(View.GONE);
                mMusicDetailsView.setVisibility(View.VISIBLE);

                ByteBuffer buffer = album.getCover();
                byte[] coverData = buffer.array();

                Bitmap prevBitmap = mAlbumCoverBitmap;
                mAlbumCoverBitmap = BitmapFactory.decodeByteArray(coverData, 0, coverData.length);
                mAlbumCoverView.setImageBitmap(mAlbumCoverBitmap);
                if (prevBitmap != null) {
                    prevBitmap.recycle();
                }

                mAlbumTitleView.setText(album.getTitle());
                mArtistTitleView.setText(album.getArtist());
                mTrackTitleView.setText(song.getTitle());

                mTrackProgressView.setMax(song.getDuration());
                mTrackProgressView.setProgress(playbackInfo.getTime());

                String timeText = TimeUtils.milliSecondsToTimer(playbackInfo.getTime()) + "/" +
                        TimeUtils.milliSecondsToTimer(song.getDuration());

                mTrackProgressTextView.setText(timeText);

            } else {
                mNoTrackSelectedView.setVisibility(View.VISIBLE);
                mMusicDetailsView.setVisibility(View.GONE);
            }
        } else {
            setDetailsVisible(false);
        }
    }

}


text:
from datetime import datetime
from multiprocessing import Queue
from typing import Optional
from logging import getLogger
from sqlalchemy import desc

from qkoubot.models import ServerErrorLog, Session
from static import LOGIN_FAILURE_TWEET_INTERVAL

class LoginFailureLog(object):
    """
    ログイン試行に失敗したときに適切にロギングするためのクラス.
    self.newest_failureで常に最新の障害情報を保持する.
    """
    def __init__(self, queue: Queue):
        self.last_confirmed = datetime.now()
        self.tweetable = False
        self.logger = getLogger("LoginFailureLogger")
        self.queue = queue
        self.newest_failure = self.__get_newest_failure()  # type: ServerErrorLog

    def __get_newest_failure(self) -> ServerErrorLog:
        """
        最新のログイン失敗情報を取得.
        Returns:
            最新のログイン失敗情報.無ければNoneを返す.
        """
        def init() -> ServerErrorLog:
            """新しいサーバログオブジェクトを返す"""
            new = ServerErrorLog("init", created_at=self.last_confirmed)
            new.is_fixed = True
            session.add(new)
            session.commit()
            return new
        with Session() as session:
            newest = session.query(ServerErrorLog)\
                .order_by(desc(ServerErrorLog.created_at))\
                .limit(1).first()  # type: Optional[ServerErrorLog]
            if newest is None:
                self.logger.debug("Create new ServerErrorLog object.")
                return init()
            elif (self.last_confirmed - newest.last_confirmed).total_seconds() > 3600:
                # 古いデータは無かったことにする.
                self.logger.debug("Reset ServerErrorLog object. Last confirmation is 3600 seconds ago.")
                return init()
            else:
                return newest

    def __create_new_failure_log(self, e: str):
        """
        新規情報の作成.

        Args:
            e: Exceptionの中身
        """
        with Session() as session:
            latest = ServerErrorLog(e, created_at=self.last_confirmed)
            session.add(latest)
            session.commit()
        self.newest_failure = latest

    def __update_failure_log(self) -> bool:
        """
        ログイン失敗情報をアップデートする.

        Returns:
            最終ツイート時刻と現在時刻がLOGIN_FAILURE_TWEET_INTERVAL以上差があったときTrue.それ以外ではFalse.
        """
        with Session() as session:
            session.add(self.newest_failure)
            self.newest_failure.last_confirmed = self.last_confirmed
            if (self.last_confirmed - self.newest_failure.tweeted_at).total_seconds() > LOGIN_FAILURE_TWEET_INTERVAL:
                self.newest_failure.tweeted_at = self.last_confirmed
                session.commit()
                return True
            else:
                session.commit()
                return False

    def set_fixed(self):
        """
        ログインに成功したときに呼ばれる.
        """
        now = datetime.now()
        with Session() as session:
            session.add(self.newest_failure)
            if self.newest_failure.is_fixed:
                self.logger.debug("All login and scraping process are success.")
                self.newest_failure.last_confirmed = now
            else:
                self.logger.info("[RECOVERED] Error has been recovered at {t}"
                                 .format(t=now.strftime("%Y/%m/%d %H:%M:%S")))
                self.newest_failure.is_fixed = True
                self.newest_failure.fixed_at = now
                self.newest_failure.last_confirmed = now
                self.newest_failure.tweeted_at = now
                if self.tweetable:
                    self.queue.put(str(self.newest_failure))
            session.commit()

    def error_occurs(self, e: str):
        """
        エラー発生時に呼ばれる関数.
        最新のServerErrorLog.is_fixedに応じて新規作成または既存情報を更新.場合に応じてツイートするためにQueueに追加する.

        Args:
            e: Exceptionの中身
        """
        self.logger.warning("[ERROR] Login or scraping failure occurs.")
        self.last_confirmed = datetime.now()
        if self.newest_failure.is_fixed:
            self.__create_new_failure_log(e)
            update = True
        else:
            update = self.__update_failure_log()
        if self.tweetable and update:
            self.queue.put(str(self.newest_failure))
        self.logger.warning(self.newest_failure.__repr__())


text:
using System;
using System.Data.SqlClient;
using System.Text;
using FlitBit.Data.Catalog;
using FlitBit.Data.DataModel;
using FlitBit.Data.Meta;
using FlitBit.Data.Tests.Catalog.Models;
using FlitBit.Emit;
using FlitBit.Wireup;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FlitBit.Data.Tests.Catalog
{
	[TestClass]
	public class MappedTypeTests
	{
		[TestInitialize]
		public void Initialize()
		{
			WireupCoordinator.SelfConfigure();
			// force the dynamic assembly to disk so we can put eyeballs on the code...
			RuntimeAssemblies.WriteDynamicAssemblyOnExit = true;
		}

		[TestMethod]
		public void TestMethod1()
		{
			var mapping = Mappings.Instance.ForType<IMappedType>();
			mapping.ConnectionName = "test-data";

			Assert.IsNotNull(mapping);
			Assert.IsNotNull(mapping.Columns);

			var binder = mapping.GetBinder();
			var builder = new StringBuilder(2000);
			binder.BuildDdlBatch(builder);
			var sql = builder.ToString();
			Assert.IsNotNull(mapping.ConcreteType);
			Assert.IsNotNull(sql);

			var all = new AllMappedTypeCommand();
			var create = new CreateMappedTypeCommand();
			var update = new UpdateMappedTypeCommand();
			var readByType = new ReadMappedTypeByRuntimeTypeCommand();

			using (var cx = DbContext.NewContext())
			{
				using (var cn = cx.SharedOrNewConnection<SqlConnection>("test-data"))
				{
					var them = all.ExecuteMany(cx, cn, QueryBehavior.Default);
					Assert.IsNotNull(them);
					Assert.IsTrue(them.Succeeded);

					var existing = readByType.ExecuteSingle(cx, cn, typeof(IMappedType));
					if (existing != null)
					{
						var ver = typeof(IMappedType).Assembly
																				.GetName()
																				.Version;
						if (existing.LatestVersion == ver.ToString(3))
						{
							existing.LatestVersion = new Version(ver.Major, ver.Minor, ver.Build + 1).ToString();
						}
						else
						{
							existing.LatestVersion = ver.ToString(3);
						}
						update.ExecuteSingle(cx, cn, existing);
					}
					else
					{
						var model = new IMappedTypeDataModel();
						model.Catalog = "unitest";
						model.LatestVersion = typeof(IMappedType).Assembly.GetName()
																										.Version.ToString(3);
						model.Schema = "OrmCatalog";
						model.MappedTable = "MappedType";
						model.RuntimeType = typeof(IMappedType);
						model.OriginalVersion = model.LatestVersion;
						model.ReadObjectName = "MappedType";
						model.Strategy = MappingStrategy.OneClassOneTable;

						var created = create.ExecuteSingle(cx, cn, model);
						Assert.IsNotNull(created);
					}
				}
			}
		}
	}
}


text:
package hu.belicza.andras.sc2gearsdb.apiuser.client;

import hu.belicza.andras.sc2gearsdb.apiuser.client.beans.ApiCallStatFilters;
import hu.belicza.andras.sc2gearsdb.apiuser.client.beans.ApiCallStatInfo;
import hu.belicza.andras.sc2gearsdb.apiuser.client.beans.ApiUserInfo;
import hu.belicza.andras.sc2gearsdb.apiuser.client.beans.QuotaAndPaymentsInfo;
import hu.belicza.andras.sc2gearsdb.apiuser.client.beans.SettingsInfo;
import hu.belicza.andras.sc2gearsdb.common.client.RpcResult;
import hu.belicza.andras.sc2gearsdb.common.client.pagingtable.EntityListResult;
import hu.belicza.andras.sc2gearsdb.common.client.pagingtable.PageInfo;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * The client side stub for the RPC service.
 *
 * @author Andras Belicza
 *
 * @see ApiUserServiceAsync
 */
@RemoteServiceRelativePath("apiusersrv")
public interface ApiUserService extends RemoteService {

	/**
	 * Returns the API user info.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @return the API user info
	 */
	RpcResult< ApiUserInfo > getApiUserInfo( String sharedApiAccount );

	/**
	 * Returns the list of API call stats.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @param pageInfo page info to return
	 * @param filters  API call stat filters to be applied
	 * @return the list result of API call stats
	 */
	RpcResult< EntityListResult< ApiCallStatInfo > > getApiCallStatList( String sharedApiAccount, PageInfo pageInfo, ApiCallStatFilters filters );

	/**
	 * Returns the API user quota info.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @return the API user quota info
	 */
	RpcResult< QuotaAndPaymentsInfo > getQuotaAndPaymentsInfo( String sharedApiAccount );

	/**
	 * Returns the API key of the logged in API user.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @return the API key of the logged in API user or null if some errors occurred
	 */
	RpcResult< String > getApiKey( String sharedApiAccount );

	/**
	 * Generates a new API key.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @return the new API key or null if some error occurred
	 */
	RpcResult< String > generateNewApiKey( String sharedApiAccount );

	/**
	 * Returns the settings of the API user.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @return the settings of the API user or null if some errors occurred
	 */
	RpcResult< SettingsInfo > getSettings( String sharedApiAccount );

	/**
	 * Saves the settings.
	 * @param sharedApiAccount Google account to access in case we're viewing someone else's account; null otherwise
	 * @param settingsInfo settings to save
	 */
	RpcResult< Void > saveSettings( String sharedApiAccount, SettingsInfo settingsInfo );

}


text:
import _ from 'lodash';

export class GroupUpdateReducer {
  reduce(json, state) {
    let data = _.get(json, 'group-update', false);
    if (data) {
      this.add(data, state);
      this.remove(data, state);
      this.bundle(data, state);
      this.unbundle(data, state);
      this.keys(data, state);
      this.path(data, state);
    }
  }

  add(json, state) {
    let data = _.get(json, 'add', false);
    if (data) {
      for (let member of data.members) {
        state.groups[data.path].add(member);
      }
    }
  }

  remove(json, state) {
    let data = _.get(json, 'remove', false);
    if (data) {
      for (let member of data.members) {
        state.groups[data.path].delete(member);
      }
    }
  }

  bundle(json, state) {

    let data = _.get(json, 'bundle', false);
    if (data) {
      state.groups[data.path] = new Set();
    }
  }

  unbundle(json, state) {
    let data = _.get(json, 'unbundle', false);
    if (data) {
      delete state.groups[data.path];
    }
  }

  keys(json, state) {
    let data = _.get(json, 'keys', false);
    if (data) {
      state.groupKeys = new Set(data.keys);
    }
  }

  path(json, state) {
    let data = _.get(json, 'path', false);
    if (data) {
      state.groups[data.path] = new Set([data.members]);
    }
  }

}


text:
namespace redpaperclip {
namespace core {
namespace local {

  using namespace std;

  const locale get_utf8_locale() {
    // This seems the most likely to exist utf-8 locale, but still may not
    try {
      return locale("en_US.UTF-8");
    } catch(runtime_error e) {
      throw("Owing to lazy programming, you currently require the en_US.UTF-8 locale installed for redpaperclip to work properly. Sorry about that.");
    }
  }

  const locale get_c_locale() {
    // Guaranteed to exist and treat characters as 1 byte
    return locale("C");
  }

  const ctype<wchar_t> &get_wchar_facet(std::locale l) {
    return use_facet< ctype<wchar_t> >(l);
  }

  const ctype<char> &get_char_facet(std::locale l) {
    return use_facet< ctype<char> >(l);
  }

  wstring read_utf8(const string &str) {
    auto l = get_utf8_locale();
    wostringstream wstm;
    wstm.imbue(l);
    auto facet = &get_wchar_facet(l);
    for( size_t i=0 ; i<str.size() ; ++i )
      wstm << facet->widen( str[i] );
    return wstm.str();
  }

  string write_utf8(const wstring &str) {
    auto l = get_c_locale();
    ostringstream stm ;
    stm.imbue(l);
    auto facet = &get_char_facet(l);
    for(size_t i=0 ; i<str.size() ; ++i)
      stm << facet->narrow(str[i], 0);
    return stm.str();
  }

}
}
}


text:
/* Memory layout of a zipmap, for the map "foo" => "bar", "hello" => "world":
 *
 * <zmlen><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
 *
 * <zmlen> is 1 byte length that holds the current size of the zipmap.
 * When the zipmap length is greater than or equal to 254, this value
 * is not used and the zipmap needs to be traversed to find out the length.
 *
 * <len> is the length of the following string (key or value).
 * <len> lengths are encoded in a single value or in a 5 bytes value.
 * If the first byte value (as an unsigned 8 bit value) is between 0 and
 * 252, it's a single-byte length. If it is 253 then a four bytes unsigned
 * integer follows (in the host byte ordering). A value of 255 is used to
 * signal the end of the hash. The special value 254 is used to mark
 * empty space that can be used to add new key/value pairs.
 *
 * <free> is the number of free unused bytes after the string, resulting
 * from modification of values associated to a key. For instance if "foo"
 * is set to "bar", and later "foo" will be set to "hi", it will have a
 * free byte to use if the value will enlarge again later, or even in
 * order to add a key/value pair if it fits.
 *
 * <free> is always an unsigned 8 bit number, because if after an
 * update operation there are more than a few free bytes, the zipmap will be
 * reallocated to make sure it is as small as possible.
 *
 * The most compact representation of the above two elements hash is actually:
 *
 * "\x02\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
 *
 * Note that because keys and values are prefixed length "objects",
 * the lookup will take O(N) where N is the number of elements
 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
 * This lowers the constant times considerably.
 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zmalloc.h"
#include "endianconv.h"
#ifdef _WIN32
#define inline __inline
#endif

#define ZIPMAP_BIGLEN 254
#define ZIPMAP_END 255

/* The following defines the max value for the <free> field described in the
 * comments above, that is, the max number of trailing bytes in a value. */
#define ZIPMAP_VALUE_MAX_FREE 4

/* The following macro returns the number of bytes needed to encode the length
 * for the integer value _l, that is, 1 byte for lengths < ZIPMAP_BIGLEN and
 * 5 bytes for all the other lengths. */
#define ZIPMAP_LEN_BYTES(_l) (((_l) < ZIPMAP_BIGLEN) ? 1 : sizeof(unsigned int)+1)

/* Create a new empty zipmap. */
unsigned char *zipmapNew(void) {
    unsigned char *zm = zmalloc(2);

    zm[0] = 0; /* Length */
    zm[1] = ZIPMAP_END;
    return zm;
}

/* Decode the encoded length pointed by 'p' */
static unsigned int zipmapDecodeLength(unsigned char *p) {
    unsigned int len = *p;

    if (len < ZIPMAP_BIGLEN) return len;
    memcpy(&len,p+1,sizeof(unsigned int));
    memrev32ifbe(&len);
    return len;
}

/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
 * the amount of bytes required to encode such a length. */
static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
    if (p == NULL) {
        return ZIPMAP_LEN_BYTES(len);
    } else {
        if (len < ZIPMAP_BIGLEN) {
            p[0] = len;
            return 1;
        } else {
            p[0] = ZIPMAP_BIGLEN;
            memcpy(p+1,&len,sizeof(len));
            memrev32ifbe(p+1);
            return 1+sizeof(len);
        }
    }
}

/* Search for a matching key, returning a pointer to the entry inside the
 * zipmap. Returns NULL if the key is not found.
 *
 * If NULL is returned, and totlen is not NULL, it is set to the entire
 * size of the zimap, so that the calling function will be able to
 * reallocate the original zipmap to make room for more entries. */
static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
    unsigned char *p = zm+1, *k = NULL;
    unsigned int l,llen;

    while(*p != ZIPMAP_END) {
        unsigned char free;

        /* Match or skip the key */
        l = zipmapDecodeLength(p);
        llen = zipmapEncodeLength(NULL,l);
        if (key != NULL && k == NULL && l == klen && !memcmp(p+llen,key,l)) {
            /* Only return when the user doesn't care
             * for the total length of the zipmap. */
            if (totlen != NULL) {
                k = p;
            } else {
                return p;
            }
        }
        p += llen+l;
        /* Skip the value as well */
        l = zipmapDecodeLength(p);
        p += zipmapEncodeLength(NULL,l);
        free = p[0];
        p += l+1+free; /* +1 to skip the free byte */
    }
    if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
    return k;
}

static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
    unsigned int l;

    l = klen+vlen+3;
    if (klen >= ZIPMAP_BIGLEN) l += 4;
    if (vlen >= ZIPMAP_BIGLEN) l += 4;
    return l;
}

/* Return the total amount used by a key (encoded length + payload) */
static unsigned int zipmapRawKeyLength(unsigned char *p) {
    unsigned int l = zipmapDecodeLength(p);
    return zipmapEncodeLength(NULL,l) + l;
}

/* Return the total amount used by a value
 * (encoded length + single byte free count + payload) */
static unsigned int zipmapRawValueLength(unsigned char *p) {
    unsigned int l = zipmapDecodeLength(p);
    unsigned int used;

    used = zipmapEncodeLength(NULL,l);
    used += p[used] + 1 + l;
    return used;
}

/* If 'p' points to a key, this function returns the total amount of
 * bytes used to store this entry (entry = key + associated value + trailing
 * free space if any). */
static unsigned int zipmapRawEntryLength(unsigned char *p) {
    unsigned int l = zipmapRawKeyLength(p);
    return l + zipmapRawValueLength(p+l);
}

static inline unsigned char *zipmapResize(unsigned char *zm, unsigned int len) {
    zm = zrealloc(zm, len);
    zm[len-1] = ZIPMAP_END;
    return zm;
}

/* Set key to value, creating the key if it does not already exist.
 * If 'update' is not NULL, *update is set to 1 if the key was
 * already preset, otherwise to 0. */
unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
    unsigned int zmlen, offset;
    unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
    unsigned int empty, vempty;
    unsigned char *p;

    freelen = reqlen;
    if (update) *update = 0;
    p = zipmapLookupRaw(zm,key,klen,&zmlen);
    if (p == NULL) {
        /* Key not found: enlarge */
        zm = zipmapResize(zm, zmlen+reqlen);
        p = zm+zmlen-1;
        zmlen = zmlen+reqlen;

        /* Increase zipmap length (this is an insert) */
        if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;
    } else {
        /* Key found. Is there enough space for the new value? */
        /* Compute the total length: */
        if (update) *update = 1;
        freelen = zipmapRawEntryLength(p);
        if (freelen < reqlen) {
            /* Store the offset of this key within the current zipmap, so
             * it can be resized. Then, move the tail backwards so this
             * pair fits at the current position. */
            offset = (unsigned int)(p-zm);
            zm = zipmapResize(zm, zmlen-freelen+reqlen);
            p = zm+offset;

            /* The +1 in the number of bytes to be moved is caused by the
             * end-of-zipmap byte. Note: the *original* zmlen is used. */
            memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
            zmlen = zmlen-freelen+reqlen;
            freelen = reqlen;
        }
    }

    /* We now have a suitable block where the key/value entry can
     * be written. If there is too much free space, move the tail
     * of the zipmap a few bytes to the front and shrink the zipmap,
     * as we want zipmaps to be very space efficient. */
    empty = freelen-reqlen;
    if (empty >= ZIPMAP_VALUE_MAX_FREE) {
        /* First, move the tail <empty> bytes to the front, then resize
         * the zipmap to be <empty> bytes smaller. */
        offset = (unsigned int)(p-zm);
        memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
        zmlen -= empty;
        zm = zipmapResize(zm, zmlen);
        p = zm+offset;
        vempty = 0;
    } else {
        vempty = empty;
    }

    /* Just write the key + value and we are done. */
    /* Key: */
    p += zipmapEncodeLength(p,klen);
    memcpy(p,key,klen);
    p += klen;
    /* Value: */
    p += zipmapEncodeLength(p,vlen);
    *p++ = vempty;
    memcpy(p,val,vlen);
    return zm;
}

/* Remove the specified key. If 'deleted' is not NULL the pointed integer is
 * set to 0 if the key was not found, to 1 if it was found and deleted. */
unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
    unsigned int zmlen, freelen;
    unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
    if (p) {
        freelen = zipmapRawEntryLength(p);
        memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
        zm = zipmapResize(zm, zmlen-freelen);

        /* Decrease zipmap length */
        if (zm[0] < ZIPMAP_BIGLEN) zm[0]--;

        if (deleted) *deleted = 1;
    } else {
        if (deleted) *deleted = 0;
    }
    return zm;
}

/* Call before iterating through elements via zipmapNext() */
unsigned char *zipmapRewind(unsigned char *zm) {
    return zm+1;
}

/* This function is used to iterate through all the zipmap elements.
 * In the first call the first argument is the pointer to the zipmap + 1.
 * In the next calls what zipmapNext returns is used as first argument.
 * Example:
 *
 * unsigned char *i = zipmapRewind(my_zipmap);
 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
 *     printf("%d bytes key at $p\n", klen, key);
 *     printf("%d bytes value at $p\n", vlen, value);
 * }
 */
unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
    if (zm[0] == ZIPMAP_END) return NULL;
    if (key) {
        *key = zm;
        *klen = zipmapDecodeLength(zm);
        *key += ZIPMAP_LEN_BYTES(*klen);
    }
    zm += zipmapRawKeyLength(zm);
    if (value) {
        *value = zm+1;
        *vlen = zipmapDecodeLength(zm);
        *value += ZIPMAP_LEN_BYTES(*vlen);
    }
    zm += zipmapRawValueLength(zm);
    return zm;
}

/* Search a key and retrieve the pointer and len of the associated value.
 * If the key is found the function returns 1, otherwise 0. */
int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
    unsigned char *p;

    if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
    p += zipmapRawKeyLength(p);
    *vlen = zipmapDecodeLength(p);
    *value = p + ZIPMAP_LEN_BYTES(*vlen) + 1;
    return 1;
}

/* Return 1 if the key exists, otherwise 0 is returned. */
int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
    return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
}

/* Return the number of entries inside a zipmap */
unsigned int zipmapLen(unsigned char *zm) {
    unsigned int len = 0;
    if (zm[0] < ZIPMAP_BIGLEN) {
        len = zm[0];
    } else {
        unsigned char *p = zipmapRewind(zm);
        while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;

        /* Re-store length if small enough */
        if (len < ZIPMAP_BIGLEN) zm[0] = len;
    }
    return len;
}

/* Return the raw size in bytes of a zipmap, so that we can serialize
 * the zipmap on disk (or everywhere is needed) just writing the returned
 * amount of bytes of the C array starting at the zipmap pointer. */
size_t zipmapBlobLen(unsigned char *zm) {
    unsigned int totlen;
    zipmapLookupRaw(zm,NULL,0,&totlen);
    return totlen;
}

#ifdef ZIPMAP_TEST_MAIN
void zipmapRepr(unsigned char *p) {
    unsigned int l;

    printf("{status %u}",*p++);
    while(1) {
        if (p[0] == ZIPMAP_END) {
            printf("{end}");
            break;
        } else {
            unsigned char e;

            l = zipmapDecodeLength(p);
            printf("{key %u}",l);
            p += zipmapEncodeLength(NULL,l);
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
            p += l;

            l = zipmapDecodeLength(p);
            printf("{value %u}",l);
            p += zipmapEncodeLength(NULL,l);
            e = *p++;
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
            p += l+e;
            if (e) {
                printf("[");
                while(e--) printf(".");
                printf("]");
            }
        }
    }
    printf("\n");
}

int main(void) {
    unsigned char *zm;

    zm = zipmapNew();

    zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
    zipmapRepr(zm);

    zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
    zipmapRepr(zm);
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
    zipmapRepr(zm);
    zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
    zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
    zipmapRepr(zm);
    zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
    zipmapRepr(zm);

    printf("\nLook up large key:\n");
    {
        unsigned char buf[512];
        unsigned char *value;
        unsigned int vlen, i;
        for (i = 0; i < 512; i++) buf[i] = 'a';

        zm = zipmapSet(zm,buf,512,(unsigned char*) "long",4,NULL);
        if (zipmapGet(zm,buf,512,&value,&vlen)) {
            printf("  <long key> is associated to the %d bytes value: %.*s\n",
                vlen, vlen, value);
        }
    }

    printf("\nPerform a direct lookup:\n");
    {
        unsigned char *value;
        unsigned int vlen;

        if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
            printf("  foo is associated to the %d bytes value: %.*s\n",
                vlen, vlen, value);
        }
    }
    printf("\nIterate through elements:\n");
    {
        unsigned char *i = zipmapRewind(zm);
        unsigned char *key, *value;
        unsigned int klen, vlen;

        while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
            printf("  %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
        }
    }
    return 0;
}
#endif


text:
//
//  SNEmotionTool.m
//  webd
//
//  Created by 普伴 on 15/10/9.
//  Copyright © 2015年 Puban. All rights reserved.
//

#import "SNEmotionTool.h"
#import "SNEmotion.h"
#import "MJExtension.h"

#define SNRecentFilepath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"recent_emotions.data"]

@implementation SNEmotionTool

/** 默认表情 */
static NSArray *_defaultEmotions;
/** emoji表情 */
static NSArray *_emojiEmotions;
/** 浪小花表情 */
static NSArray *_lxhEmotions;
/** 最近表情 */
static NSMutableArray *_recentEmotions;

+ (NSArray *)defaultEmotions
{
    if (!_defaultEmotions) {
        NSString *plist = [[NSBundle mainBundle] pathForResource:@"EmotionIcons/default/info.plist" ofType:nil];
        _defaultEmotions = [SNEmotion objectArrayWithFile:plist];
        [_defaultEmotions makeObjectsPerformSelector:@selector(setDirection:) withObject:@"EmotionIcons/default"];
    }
    return _defaultEmotions;
}
@end


text:
package com.salesmanager.shop.populator.catalog;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.Validate;

import com.salesmanager.core.business.exception.ConversionException;
import com.salesmanager.core.business.services.catalog.product.ProductService;
import com.salesmanager.core.business.services.customer.CustomerService;
import com.salesmanager.core.business.services.reference.language.LanguageService;
import com.salesmanager.core.business.utils.AbstractDataPopulator;
import com.salesmanager.core.model.catalog.product.Product;
import com.salesmanager.core.model.catalog.product.review.ProductReview;
import com.salesmanager.core.model.catalog.product.review.ProductReviewDescription;
import com.salesmanager.core.model.customer.Customer;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.shop.model.catalog.product.PersistableProductReview;
import com.salesmanager.shop.utils.DateUtil;

public class PersistableProductReviewPopulator extends
		AbstractDataPopulator<PersistableProductReview, ProductReview> {

	private CustomerService customerService;

	private ProductService productService;

	private LanguageService languageService;

	public LanguageService getLanguageService() {
		return languageService;
	}

	public void setLanguageService(LanguageService languageService) {
		this.languageService = languageService;
	}

	@Override
	public ProductReview populate(PersistableProductReview source,
			ProductReview target, MerchantStore store, Language language)
			throws ConversionException {

		Validate.notNull(customerService,"customerService cannot be null");
		Validate.notNull(productService,"productService cannot be null");
		Validate.notNull(languageService,"languageService cannot be null");
		Validate.notNull(source.getRating(),"Rating cannot bot be null");

		try {

			if(target==null) {
				target = new ProductReview();
			}

			Customer customer = customerService.getById(source.getCustomerId());

			//check if customer belongs to store
			if(customer ==null || customer.getMerchantStore().getId().intValue()!=store.getId().intValue()) {
				throw new ConversionException("Invalid customer id for the given store");
			}

			if(source.getDate() == null) {
				String date = DateUtil.formatDate(new Date());
				source.setDate(date);
			}
			target.setReviewDate(DateUtil.getDate(source.getDate()));
			target.setCustomer(customer);
			target.setReviewRating(source.getRating());

			Product product = productService.getById(source.getProductId());

			//check if product belongs to store
			if(product ==null || product.getMerchantStore().getId().intValue()!=store.getId().intValue()) {
				throw new ConversionException("Invalid product id for the given store");
			}

			target.setProduct(product);

			Language lang = languageService.getByCode(language.getCode());
			if(lang ==null) {
				throw new ConversionException("Invalid language code, use iso codes (en, fr ...)");
			}

			ProductReviewDescription description = new ProductReviewDescription();
			description.setDescription(source.getDescription());
			description.setLanguage(lang);
			description.setName("-");
			description.setProductReview(target);

			Set<ProductReviewDescription> descriptions = new HashSet<ProductReviewDescription>();
			descriptions.add(description);

			target.setDescriptions(descriptions);

			return target;

		} catch (Exception e) {
			throw new ConversionException("Cannot populate ProductReview", e);
		}

	}

	@Override
	protected ProductReview createTarget() {
		return null;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

}


text:
$JSKK.Class.create
(
	{
		$namespace:	'nutsnbolts.widget.select',
		$name:		'Config'
	}
)
(
	{},
	{
		init: function()
		{
			$application.registerAction('widget.select.config.addOption',	this.addOption.bind(this))
						.registerAction('widget.select.config.removeOption',this.removeOption.bind(this));
		},
		addOption: function(btn)
		{
			var	widgetIndex	=btn.parents('div[data-index]').data('index'),
				optionIndex	=btn.siblings('table').find('tbody tr').length;
			btn.siblings('table').find('tbody').append
			(
				[
					'
',
						'',
							'<input type="text" class="input-medium" value="" data-prompt-position="topLeft" class="validate[required]" name="widget['+widgetIndex+'][config][options]['+optionIndex+'][label]">',
						'	',
						'',
							'<input type="text" class="input-medium" value="" data-prompt-position="topLeft" class="validate[required]" name="widget['+widgetIndex+'][config][options]['+optionIndex+'][value]">',
						'	',
						'',
							'<button data-action="widget.select.config.removeOption" class="btn btn-danger btn-mini" type="button">×</button>',
						'	',
					'
'
				].join('')
			);
		},
		removeOption: function(btn)
		{
			var table=btn.parents('table');
			btn.parents('tr').remove();
			this.reindex(table);
		},
		reindex: function(table)
		{
			var widgetIndex=table.parents('[data-index]').data('index');
			table.find('tr:not(:first)').each
			(
				function(optionIndex,tr)
				{
					$(tr).find('input').each
					(
						function(i,input)
						{
							if ($(input).attr('name').indexOf('label')!==-1)
							{
								$(input).attr('name','widget['+widgetIndex+'][config][options]['+optionIndex+'][label]');
							}
							else
							{
								$(input).attr('name','widget['+widgetIndex+'][config][options]['+optionIndex+'][value]');
							}
						}
					);
				}
			);
		}
	}
);


text:
<?php
namespace Kunstmaan\AdminListBundle\Tests\AdminList;

use Kunstmaan\AdminListBundle\AdminList\AdminListFactory;

use Kunstmaan\AdminListBundle\AdminList\Configurator\AdminListConfiguratorInterface;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2012-09-26 at 13:21:32.
 */
class AdminListFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AdminListFactory
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new AdminListFactory;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Kunstmaan\AdminListBundle\AdminList\AdminListFactory::createList
     */
    public function testCreateList()
    {
        /* @var AdminListConfiguratorInterface $mockConfig */
        $mockConfig = $this->getMock('Kunstmaan\AdminListBundle\AdminList\Configurator\AdminListConfiguratorInterface');
        $list = $this->object->createList($mockConfig);

        $this->assertInstanceOf('Kunstmaan\AdminListBundle\AdminList\AdminList', $list);
    }
}


text:
require 'test_helper'

class UserPolicyTest < PolicyAssertions::Test
  def setup
    @regular_user = users(:regular_user)
    @user1 = users(:user1)
    @admin_user = users(:admin_user)
    @available_actions = [:index, :new, :create, :edit, :update, :destroy, :show]
  end

  def test_index
    #Only admins should be able to get index.
    assert_permit @admin_user, User
    refute_permit @regular_user, User
    refute_permit nil, User
  end

  def test_edit_and_show_and_update
    #Admins can edit self and others.
    assert_permit @admin_user, @admin_user
    assert_permit @admin_user, @regular_user

    #Regular users can edit self, but not others.
    assert_permit @regular_user, @regular_user
    refute_permit @regular_user, @user1

    #Anon should not be able to edit anyone.
    refute_permit nil, @regular_user
  end

  def test_destroy
    #Admins should be able to destroy records other than their own.
    refute_permit @admin_user, @admin_user
    assert_permit @admin_user, @regular_user

    #Regular users are not permitted to destroy users.
    refute_permit @regular_user, @regular_user
    refute_permit @regular_user, @user1

    #Anon are not permitted to destroy users.
    refute_permit nil, @regular_user
  end

  def test_create_and_new
    #Admins and anon should be able to create a user.
    assert_permit @admin_user, User
    refute_permit @regular_user, User
    assert_permit nil, User
  end

  def test_strong_parameters
    user_attributes = @regular_user.attributes
    admin_params = [:id, :first_name, :last_name, :email, :password, :active, :admin, :admin_selectable_only]
    regular_user_params = [:id, :first_name, :last_name, :email, :password]
    anonymous_params = [:id, :first_name, :last_name, :email, :password]

    assert_strong_parameters(@admin_user, User, user_attributes, admin_params)

    assert_strong_parameters(@regular_user, User, user_attributes, regular_user_params)

    assert_strong_parameters(nil, User, user_attributes, anonymous_params)
  end

end


text:
package org.openmuc.framework.dataaccess;

import org.openmuc.framework.data.Record;

public interface ReadRecordContainer {

    Record getRecord();

    Channel getChannel();

}


text: export { OptionalByte } from './optional_scalars/optional-byte';


text:
*Author: @JensLincke*

## #Evolution #MarkdownApp #DirectorySpecificApplication

![](querkoepfe_rename_app.png)

<http://localhost:9005/Dropbox/Music/dlf/Querkoepfe/index.md>

(INFO: for this application to work, Lively4 does not have to be installed on localhost... Just a lively4 compatible file server, e.g. that can list (OPTIONS), GET, PUT, DELETE, and optionally MOVE files). In webwerkstatt (Lively2) we used apache webdav for it... our current protocol is custom.

An evening of scripting looked like this....

| filename| date| user | host | size|
|-------|---|--|---|--|
| index.md | 22:10 | Bearbeitet von Jens Lincke | Desktop | 3,71 KB |
| index.md | 22:01 | Bearbeitet von Jens Lincke | Desktop | 3,68 KB |
| index.md | 21:56 | Bearbeitet von Jens Lincke | Desktop | 3,52 KB |
| index.md | 21:54 | Bearbeitet von Jens Lincke | Desktop | 3,36 KB |
| index.md | 21:51 | Bearbeitet von Jens Lincke | Desktop | 3,3 KB |
| index.md | 21:48 | Bearbeitet von Jens Lincke | Desktop | 3,11 KB |
| index.md | 21:47 | Bearbeitet von Jens Lincke | Desktop | 3,12 KB |
| index.md | 21:43 | Bearbeitet von Jens Lincke | Desktop | 2,85 KB |
| index.md | 21:42 | Bearbeitet von Jens Lincke | Desktop | 2,75 KB |
| index.md | 21:40 | Bearbeitet von Jens Lincke | Desktop | 2,65 KB |
| index.md | 21:33 | Bearbeitet von Jens Lincke | Desktop | 2,48 KB |
| index.md | 21:30 | Bearbeitet von Jens Lincke | Desktop | 2,3 KB |
| index.md | 21:29 | Bearbeitet von Jens Lincke | Desktop | 2,3 KB |
| index.md | 21:19 | Bearbeitet von Jens Lincke | Desktop | 1,8 KB |
| index.md | 21:17 | Bearbeitet von Jens Lincke | Desktop | 1,29 KB |
| index.md | 21:15 | Bearbeitet von Jens Lincke | Desktop | 1,08 KB |
| index.md | 21:14 | Bearbeitet von Jens Lincke | Desktop | 1,13 KB |
| index.md | 21:12 | Bearbeitet von Jens Lincke | Desktop | 1,09 KB |
| index.md | 21:08 | Bearbeitet von Jens Lincke | Desktop | 1.011 Bytes |
| index.md | 21:06 | Bearbeitet von Jens Lincke | Desktop | 787 Bytes |
| index.md | 21:04 | Bearbeitet von Jens Lincke | Desktop | 477 Bytes |
| index.md | 21:01 | Bearbeitet von Jens Lincke | Desktop | 256 Bytes |
| index.md | 20:59 | Bearbeitet von Jens Lincke | Desktop | 185 Bytes |
| index.md | 20:57 | Hinzugefügt von Jens Lincke | Desktop | 15 Bytes |

### Starting from a simple listing of files

```javascript
var container = lively.query(this, "lively-container") var dirURL = container.getDir()

var stats

(async () => { stats = await fetch(dirURL, {method: "OPTIONS"}).then(r => r.json())

return stats.contents })()
```

### ... the script evolved in a bit over an hour into

```javascript

import Strings from 'src/client/strings.js'

class QuerkoepfeApp {

  constructor(dirURL) {
    this.dirURL = dirURL
  }

  async loadDLFQuerkoepfe(isoDate) {
    var tab = await fetch(`http://localhost:9005/Dropbox/share/DLF/extract/${isoDate}.tab`).then(r => r.text())

    var programm = tab.split(/\n/g).map(ea => ea.split(/\t/))

    var querkoepfe = programm.filter(ea => ea[1] && ea[1].startsWith("Querköpfe"))[0]

    programm.map(ea => ea[0])

    if (!querkoepfe || !querkoepfe[2]) return

    var div = <div></div>
    div.innerHTML = querkoepfe[2]
    div.querySelector("p").innerHTML.split(/<br>/)
    return div.querySelector("p").innerHTML.split(/<br>/)

  }

  async selectItem(item) {
    if (this.lastSelected) this.lastSelected.classList.remove("selected")
    item.classList.add("selected")
    this.lastSelected = item

    var m = item.textContent.match(/(20\d\d-\d\d-\d\d)/)
    if (m) {
      var isoDate = m[1]
    } else {
      return
    }

    var info = await this.loadDLFQuerkoepfe(isoDate)

    if (!info) {
      this.details.innerHTML = "no details"
    } else {
      this.details.innerHTML = JSON.stringify(info)
      this.lastSelected.info = info
    }

  }

  onItemClick(evt, item) {

    this.selectItem(item)

    // if (item.classList.contains("selected")) {
    //   item.classList.remove("selected")
    // } else {
    //   item.classList.add("selected")
    // }
  }

  async onRenameButton(evt) {
    if (!this.lastSelected || !this.lastSelected.info) return
    if (!this.lastSelected.file) return

    var rawPattern = "Wed_2105_querkoepfe"

    var filename = this.lastSelected.file.name
    if (!filename.match(rawPattern)) {
      lively.notify("file has already a custom name")
      return
    }

    var info = this.lastSelected.info
    var s ="Querkoepfe - " + info[1]
    if (info[2]) s += " - " + info[2]
    s = s.replace(/ /g, "_")
    s = s.replace(/[:.\/]/g, "_")

    s = s.replace(/_+/g, "_")

    var newFilename = filename.replace(rawPattern, s)

    var fromURL = this.dirURL + encodeURI(filename)
    var toURL = this.dirURL + encodeURI(newFilename)

    await lively.confirm("rename " + filename + " -> " + newFilename  + " in " + this.dirURL)

    var resp = await lively.files.moveFile(fromURL, toURL)
    if (resp.status == 200) {
      this.lastSelected.innerHTML = newFilename
    } else {
      this.lastSelected.style.backgroundColor = "red"
    }

    // lively.warn("not implemented yet")

  }
  async createView() {
    var stats = await fetch(this.dirURL, {method: "OPTIONS"}).then(r => r.json())

    var items = stats.contents
                  .sortBy(ea => ea.name)
                  .map(ea => {
                    var item = <li>{ea.name}</li>
                    item.file = ea
                    item.addEventListener("click", evt => this.onItemClick(evt, item))
                    return item
                  })

    var list = <ul id="list">{...items}</ul>
    var style = document.createElement("style") // #ISSUE style tags conflict with Markdown rewriting....
    style.innerHTML = `
      li.selected {
        background-color: lightgray
      }

      #pane {
        height: 100%;
      }

      #list {
        height: 400px;
        overflow: auto;
      }

    `
    this.details = <div id="details"></div>
    return <div>
        {style}
        <div id="pane">
          <div id="buttons"><button click={evt => this.onRenameButton(evt)}>rename</button></div>
          {this.details}
          {list}
        </div>
      </div>
  }

}

var container  = lively.query(this, "lively-container")
new QuerkoepfeApp(container.getDir()).createView()

```

I knew [the domain](https://lively-kernel.org/repository/webwerkstatt/users/jenslincke/DLF.xhtml), programmed similar applications before and could look at existing scripts when I ran into an issue with renaming umlauts. But this the (yet unpolished) typical kind of application I expect Lively4 users to build. Some parts of the overall application is handled outside of lively, e.g. the recording of the radio show and the downloading (and parsing) of the radio program and information. Since both approaches are long running and require full web access. Downloading and scraping other websites would is prevented by the browser and requires Lively additional help from a proxy server or in this case a shell script.

The resulting Lively4 is a markdown file that is persisted beside the data (mp3 files) it works on. When browsing the directory of the files within lively will show "index.md" file and run the application. In a funny way, this is a context specific application inside a directory... I think Windows Explorer experimented with such "Active Desktop" in the 90ies... But the time was not right yet and everybody hated it, because it slowed down the computer. And I assume was a huge security risk. Which might be the same for this application...


text:
import { Component, createElement } from 'react'
import { connectFactory } from 'fela-bindings'

import { RendererContext, ThemeContext } from './context'

export default connectFactory(
  Component,
  createElement,
  RendererContext,
  ThemeContext
)


text:
<?xml version="1.0"?>
<database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="zed" xsi:noNamespaceSchemaLocation="http://static.spryker.com/schema-01.xsd" namespace="Orm\Zed\StateMachineExample\Persistence" package="src.Orm.Zed.StateMachineExample.Persistence">

    <table name="pyz_state_machine_example_item" phpName="PyzStateMachineExampleItem" identifierQuoting="true">
        <column name="id_state_machine_example_item" required="true" type="INTEGER" autoIncrement="true" primaryKey="true"/>
        <column name="fk_state_machine_item_state" type="INTEGER" required="false"/>
        <column name="name" type="VARCHAR" required="false"/>

        <foreign-key name="pyz_state_machine_example_item-fk_state_machine_item_state" foreignTable="spy_state_machine_item_state" phpName="State" refPhpName="StateMachineItemState">
            <reference local="fk_state_machine_item_state" foreign="id_state_machine_item_state"/>
        </foreign-key>

        <id-method-parameter value="pyz_state_machine_example_item_pk_seq"/>
    </table>

</database>


text:
// flow-typed signature: de62c229601a7e7ed18e5267c0903367
// flow-typed version: <<STUB>>/semantic-release_v^8.2.0/flow_v0.58.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'semantic-release'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'semantic-release' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'semantic-release/bin/semantic-release' {
  declare module.exports: any;
}

declare module 'semantic-release/src/index' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/get-commits' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/get-registry' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/get-release-type' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/get-version-head' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/plugin-noop' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/plugins' {
  declare module.exports: any;
}

declare module 'semantic-release/src/lib/verify' {
  declare module.exports: any;
}

declare module 'semantic-release/src/post' {
  declare module.exports: any;
}

declare module 'semantic-release/src/pre' {
  declare module.exports: any;
}

// Filename aliases
declare module 'semantic-release/bin/semantic-release.js' {
  declare module.exports: $Exports<'semantic-release/bin/semantic-release'>;
}
declare module 'semantic-release/src/index.js' {
  declare module.exports: $Exports<'semantic-release/src/index'>;
}
declare module 'semantic-release/src/lib/get-commits.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/get-commits'>;
}
declare module 'semantic-release/src/lib/get-registry.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/get-registry'>;
}
declare module 'semantic-release/src/lib/get-release-type.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/get-release-type'>;
}
declare module 'semantic-release/src/lib/get-version-head.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/get-version-head'>;
}
declare module 'semantic-release/src/lib/plugin-noop.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/plugin-noop'>;
}
declare module 'semantic-release/src/lib/plugins.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/plugins'>;
}
declare module 'semantic-release/src/lib/verify.js' {
  declare module.exports: $Exports<'semantic-release/src/lib/verify'>;
}
declare module 'semantic-release/src/post.js' {
  declare module.exports: $Exports<'semantic-release/src/post'>;
}
declare module 'semantic-release/src/pre.js' {
  declare module.exports: $Exports<'semantic-release/src/pre'>;
}


text:
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.
  config.action_controller.default_url_options = { host: 'blog.dev' }

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false
  config.secret_key_base = 'd3a6cf1372e8cd53dc92f6d42f488bd0808437f9a4e14ea3ff977b948857db0f0b326d3bb86d5ff3900629b9b0ab531da669a8a2b514ed98d2133555f41bf470'

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true
    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false
    config.cache_store = :null_store
  end

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true
  config.assets.precompile += %w( clear_form.scss clean_form.js.coffee markdown_converter.js.coffee medium.js medium.min.css medium-editor-insert-plugin.min.js sortable.min.js sortable.min.js jquery.ui.widget.min.js jquery.iframe_transport.js  jquery.fileupload.min.js commons.scss fonts.scss)
  config.assets.precompile += %w( patricia_carmona_colors.scss patricia_carmona.scss modal_link_observer.js.coffee font-families.css mobile.scss patricia_carmona_mobile.scss infinite_scroll.js jquery.inifinitescroll.js)
  config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  config.action_mailer.default_url_options = { :host => 'patriciacarmona.com' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      :address              => 'smtp.gmail.com',
      :port                 => 587,
      :domain               => 'gmail.com',
      :user_name            => ENV['EMAIL_SENDER'],
      :password             => ENV['EMAIL_SENDER_PASS'],
      :authentication       => 'login',
      :enable_starttls_auto => true
  }

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  # config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end


text:
'use strict';

function ProjectListController($scope, projects, BoldedService, ProjectsService, UsersService, context, DiscussionsService) {

    let me;
    UsersService.getMe().then(function(result) {
      me = result;
    });

    $scope.items = projects.data || projects;

    var subProjects = [];
    $scope.items.forEach(function (item) {
        if (item.subProjects && item.subProjects.length > 0) {
            return subProjects = subProjects.concat(item.subProjects.filter(function (subProject) {
                return subProject !== 'undefined';
            }));
        }
    });

    $scope.loadNext = projects.next;
    $scope.loadPrev = projects.prev;

    $scope.entityName = 'projects';
    $scope.entityRowTpl = '/icu/components/project-list/project-row.html';

    var creatingStatuses = {
        NotCreated: 0,
        Creating: 1,
        Created: 2
    }

    $scope.getBoldedClass = function(entity){
      return BoldedService.getBoldedClass(entity, 'projects');
    };

    $scope.update = function(item) {
        return ProjectsService.update(item);
    }

    $scope.create = function(parent) {

        var newItem = {
            title: '',
            color: '0097A7',
            watchers: [],
            __state: creatingStatuses.NotCreated,
            __autocomplete: true
        };
        if(parent){
            newItem[parent.type] = parent.id;
        }
        return ProjectsService.create(newItem).then(function(result) {
            $scope.items.push(result);
            ProjectsService.data.push(result);
            return result;
        }).then(item => {
            if(parent && parent.type === 'discussion') {
                return DiscussionsService.getById(context.entityId)
                    .then(parentEntity => {
                        let parentParams = _.pick(parentEntity, ['watchers', 'permissions']);
                        Object.assign(item, parentParams);
                        return ProjectsService.update(item);
                    });
            } else {
                return item;
            }
        });
    };
}

angular.module('mean.icu.ui.projectlist', []).controller('ProjectListController', ProjectListController);


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F1xx_IT_H
#define __STM32F1xx_IT_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */

void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void DebugMon_Handler(void);
void SysTick_Handler(void);
void EXTI0_IRQHandler(void);
void DMA1_Channel5_IRQHandler(void);
void EXTI9_5_IRQHandler(void);
void I2C2_EV_IRQHandler(void);
void I2C2_ER_IRQHandler(void);
void USART1_IRQHandler(void);
void EXTI15_10_IRQHandler(void);
void TIM6_DAC_IRQHandler(void);

#ifdef __cplusplus
}
#endif

#endif /* __STM32F1xx_IT_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
namespace content {

class WebRtcAudioCapturer;
class WebRtcAudioRenderer;

// TODO(xians): Move the following two interfaces to webrtc so that
// libjingle can own references to the renderer and capturer.
class WebRtcAudioRendererSource {
 public:
  // Callback to get the rendered interleaved data.
  // TODO(xians): Change uint8* to int16*.
  virtual void RenderData(uint8* audio_data,
                          int number_of_channels,
                          int number_of_frames,
                          int audio_delay_milliseconds) = 0;

  // Set the format for the capture audio parameters.
  virtual void SetRenderFormat(const media::AudioParameters& params) = 0;

  // Callback to notify the client that the renderer is going away.
  virtual void RemoveAudioRenderer(WebRtcAudioRenderer* renderer) = 0;

 protected:
  virtual ~WebRtcAudioRendererSource() {}
};

class PeerConnectionAudioSink {
 public:
  // Callback to deliver the captured interleaved data.
  // |channels| contains a vector of WebRtc VoE channels.
  // |audio_data| is the pointer to the audio data.
  // |sample_rate| is the sample frequency of audio data.
  // |number_of_channels| is the number of channels reflecting the order of
  // surround sound channels.
  // |audio_delay_milliseconds| is recording delay value.
  // |current_volume| is current microphone volume, in range of |0, 255].
  // |need_audio_processing| indicates if the audio needs WebRtc AEC/NS/AGC
  // audio processing.
  // The return value is the new microphone volume, in the range of |0, 255].
  // When the volume does not need to be updated, it returns 0.
  virtual int OnData(const int16* audio_data,
                     int sample_rate,
                     int number_of_channels,
                     int number_of_frames,
                     const std::vector<int>& channels,
                     int audio_delay_milliseconds,
                     int current_volume,
                     bool need_audio_processing,
                     bool key_pressed) = 0;

  // Set the format for the capture audio parameters.
  // This is called when the capture format has changed, and it must be called
  // on the same thread as calling CaptureData().
  virtual void OnSetFormat(const media::AudioParameters& params) = 0;

 protected:
 virtual ~PeerConnectionAudioSink() {}
};

// Note that this class inherits from webrtc::AudioDeviceModule but due to
// the high number of non-implemented methods, we move the cruft over to the
// WebRtcAudioDeviceNotImpl.
class CONTENT_EXPORT WebRtcAudioDeviceImpl
    : NON_EXPORTED_BASE(public PeerConnectionAudioSink),
      NON_EXPORTED_BASE(public WebRtcAudioDeviceNotImpl),
      NON_EXPORTED_BASE(public WebRtcAudioRendererSource) {
 public:
  // The maximum volume value WebRtc uses.
  static const int kMaxVolumeLevel = 255;

  // Instances of this object are created on the main render thread.
  WebRtcAudioDeviceImpl();

  // webrtc::RefCountedModule implementation.
  // The creator must call AddRef() after construction and use Release()
  // to release the reference and delete this object.
  // Called on the main render thread.
  virtual int32_t AddRef() OVERRIDE;
  virtual int32_t Release() OVERRIDE;

  // webrtc::AudioDeviceModule implementation.
  // All implemented methods are called on the main render thread unless
  // anything else is stated.

  virtual int32_t RegisterAudioCallback(webrtc::AudioTransport* audio_callback)
      OVERRIDE;

  virtual int32_t Init() OVERRIDE;
  virtual int32_t Terminate() OVERRIDE;
  virtual bool Initialized() const OVERRIDE;

  virtual int32_t PlayoutIsAvailable(bool* available) OVERRIDE;
  virtual bool PlayoutIsInitialized() const OVERRIDE;
  virtual int32_t RecordingIsAvailable(bool* available) OVERRIDE;
  virtual bool RecordingIsInitialized() const OVERRIDE;

  // All Start/Stop methods are called on a libJingle worker thread.
  virtual int32_t StartPlayout() OVERRIDE;
  virtual int32_t StopPlayout() OVERRIDE;
  virtual bool Playing() const OVERRIDE;
  virtual int32_t StartRecording() OVERRIDE;
  virtual int32_t StopRecording() OVERRIDE;
  virtual bool Recording() const OVERRIDE;

  // Called on the AudioInputDevice worker thread.
  virtual int32_t SetMicrophoneVolume(uint32_t volume) OVERRIDE;

  // TODO(henrika): sort out calling thread once we start using this API.
  virtual int32_t MicrophoneVolume(uint32_t* volume) const OVERRIDE;

  virtual int32_t MaxMicrophoneVolume(uint32_t* max_volume) const OVERRIDE;
  virtual int32_t MinMicrophoneVolume(uint32_t* min_volume) const OVERRIDE;
  virtual int32_t StereoPlayoutIsAvailable(bool* available) const OVERRIDE;
  virtual int32_t StereoRecordingIsAvailable(bool* available) const OVERRIDE;
  virtual int32_t PlayoutDelay(uint16_t* delay_ms) const OVERRIDE;
  virtual int32_t RecordingDelay(uint16_t* delay_ms) const OVERRIDE;
  virtual int32_t RecordingSampleRate(uint32_t* samples_per_sec) const OVERRIDE;
  virtual int32_t PlayoutSampleRate(uint32_t* samples_per_sec) const OVERRIDE;

  // Sets the |renderer_|, returns false if |renderer_| already exists.
  // Called on the main renderer thread.
  bool SetAudioRenderer(WebRtcAudioRenderer* renderer);

  // Adds/Removes the capturer to the ADM.
  // TODO(xians): Remove these two methods once the ADM does not need to pass
  // hardware information up to WebRtc.
  void AddAudioCapturer(const scoped_refptr<WebRtcAudioCapturer>& capturer);
  void RemoveAudioCapturer(const scoped_refptr<WebRtcAudioCapturer>& capturer);

  // Gets the default capturer, which is the last capturer in |capturers_|.
  scoped_refptr<WebRtcAudioCapturer> GetDefaultCapturer() const;

  // Gets paired device information of the capture device for the audio
  // renderer. This is used to pass on a session id, sample rate and buffer
  // size to a webrtc audio renderer (either local or remote), so that audio
  // will be rendered to a matching output device.
  // Returns true if the capture device has a paired output device, otherwise
  // false. Note that if there are more than one open capture device the
  // function will not be able to pick an appropriate device and return false.
  bool GetAuthorizedDeviceInfoForAudioRenderer(
      int* session_id, int* output_sample_rate, int* output_buffer_size);

  const scoped_refptr<WebRtcAudioRenderer>& renderer() const {
    return renderer_;
  }
  int output_buffer_size() const {
    return output_audio_parameters_.frames_per_buffer();
  }
  int output_channels() const {
    return output_audio_parameters_.channels();
  }
  int output_sample_rate() const {
    return output_audio_parameters_.sample_rate();
  }

 private:
  typedef std::list<scoped_refptr<WebRtcAudioCapturer> > CapturerList;

  // Make destructor private to ensure that we can only be deleted by Release().
  virtual ~WebRtcAudioDeviceImpl();

  // PeerConnectionAudioSink implementation.

  // Called on the AudioInputDevice worker thread.
  virtual int OnData(const int16* audio_data,
                     int sample_rate,
                     int number_of_channels,
                     int number_of_frames,
                     const std::vector<int>& channels,
                     int audio_delay_milliseconds,
                     int current_volume,
                     bool need_audio_processing,
                     bool key_pressed) OVERRIDE;

  // Called on the AudioInputDevice worker thread.
  virtual void OnSetFormat(const media::AudioParameters& params) OVERRIDE;

  // WebRtcAudioRendererSource implementation.

  // Called on the AudioInputDevice worker thread.
  virtual void RenderData(uint8* audio_data,
                          int number_of_channels,
                          int number_of_frames,
                          int audio_delay_milliseconds) OVERRIDE;

  // Called on the main render thread.
  virtual void SetRenderFormat(const media::AudioParameters& params) OVERRIDE;
  virtual void RemoveAudioRenderer(WebRtcAudioRenderer* renderer) OVERRIDE;

  // Used to DCHECK that we are called on the correct thread.
  base::ThreadChecker thread_checker_;

  int ref_count_;

  // List of captures which provides access to the native audio input layer
  // in the browser process.
  CapturerList capturers_;

  // Provides access to the audio renderer in the browser process.
  scoped_refptr<WebRtcAudioRenderer> renderer_;

  // Weak reference to the audio callback.
  // The webrtc client defines |audio_transport_callback_| by calling
  // RegisterAudioCallback().
  webrtc::AudioTransport* audio_transport_callback_;

  // Cached values of used output audio parameters. Platform dependent.
  media::AudioParameters output_audio_parameters_;

  // Cached value of the current audio delay on the input/capture side.
  int input_delay_ms_;

  // Cached value of the current audio delay on the output/renderer side.
  int output_delay_ms_;

  // Protects |recording_|, |output_delay_ms_|, |input_delay_ms_|, |renderer_|
  // |recording_| and |microphone_volume_|.
  mutable base::Lock lock_;

  // Used to protect the racing of calling OnData() since there can be more
  // than one input stream calling OnData().
  mutable base::Lock capture_callback_lock_;

  bool initialized_;
  bool playing_;
  bool recording_;

  // Used for histograms of total recording and playout times.
  base::Time start_capture_time_;
  base::Time start_render_time_;

  // Stores latest microphone volume received in a CaptureData() callback.
  // Range is [0, 255].
  uint32_t microphone_volume_;

  DISALLOW_COPY_AND_ASSIGN(WebRtcAudioDeviceImpl);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_WEBRTC_AUDIO_DEVICE_IMPL_H_


text:
using System;
using System.Threading;

namespace vm.Aspects.Threading
{
    /// <summary>
    /// With the help of this class the developer can create a synchronized multiple readers/single writer scope by utilizing the <c>using</c> statement.
    /// </summary>
    /// <example>
    /// <code>
    /// <![CDATA[
    /// class Protected
    /// {
    ///     static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    ///     static Dictionary<string, string>; _protected = new Dictionary<string, string>();
    ///
    ///     public void Get(string key)
    ///     {
    ///         using(new ReaderSlimSync(_lock))
    ///             return _protected[key];
    ///     }
    /// }
    /// ]]>
    /// </code>
    /// </example>
    /// <seealso cref="T:System.Threading.WriterSlimSync"/>, <seealso cref="UpgradeableReaderSlimSync"/>, <seealso cref="WriterSlimSync"/>.
    sealed class ReaderSlimSync : IDisposable
    {
        readonly ReaderWriterLockSlim _readerWriterLock;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReaderSlimSync"/> class with the specified <paramref name="readerWriterLock"/> and
        /// waits indefinitely till it acquires the lock in reader mode.
        /// </summary>
        /// <param name="readerWriterLock">The reader writer lock.</param>
        public ReaderSlimSync(
            ReaderWriterLockSlim readerWriterLock)
        {
            if (readerWriterLock == null)
                throw new ArgumentNullException(nameof(readerWriterLock));

            readerWriterLock.EnterReadLock();
            _readerWriterLock = readerWriterLock;
        }

        #region IDisposable pattern implementation
        /// <summary>
        /// The flag is being set when the object gets disposed.
        /// </summary>
        /// <value>
        /// 0 - if the object is not disposed yet, any other value would mean that the object is already disposed.
        /// </value>
        int _disposed;

        /// <summary>
        /// Returns <see langword="true"/> if the object has already been disposed, otherwise <see langword="false"/>.
        /// </summary>
        public bool IsDisposed => Interlocked.CompareExchange(ref _disposed, 1, 1) == 1;

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (Interlocked.Exchange(ref _disposed, 1) == 0)
                _readerWriterLock.ExitReadLock();
        }
        #endregion
    }
}