text:
By installing [`@redux-devtools/cli`](https://github.com/reduxjs/redux-devtools/tree/master/packages/redux-devtools-cli#usage), starting the server server and launching the Redux DevTools app (`redux-devtools --open`), you can connect any remote application, even not javascript. There are some integrations for javascript like [remote-redux-devtools](https://github.com/zalmoxisus/remote-redux-devtools) and [remotedev](https://github.com/zalmoxisus/remotedev), but the plan is to deprecate them and support it out of the box from the extension without a websocket server. It is more useful for non-js apps.

### WebSocket Clients

We're using [SocketCluster](http://socketcluster.io/) for realtime communication, which provides a fast and scalable webSocket layer and a minimal pub/sub system. You need to include one of [its clients](https://github.com/SocketCluster/client-drivers) in your app to communicate with RemotedevServer. Currently there are clients for [JavaScript (NodeJS)](https://github.com/SocketCluster/socketcluster-client), [Java](https://github.com/sacOO7/socketcluster-client-java), [Python](https://github.com/sacOO7/socketcluster-client-python), [C](https://github.com/sacOO7/socketcluster-client-C), [Objective-C](https://github.com/abpopov/SocketCluster-ios-client) and [.NET/C#](https://github.com/sacOO7/SocketclusterClientDotNet).

By default, the websocket server is running on `ws://localhost:8000/socketcluster/`.

### Messaging lifecycle

#### 1. Connecting to the WebSocket server

The client driver provides a way to connect to the server via websockets (see the docs for the selected client).

##### JavaScript

```js
var socket = socketCluster.connect({
  hostname: 'localhost',
  port: 8000,
});
```

##### Python

```py
socket = Socketcluster.socket("ws://localhost:8000/socketcluster/")
socket.connect()
```

> Note that JavaScript client composes the url from `hostname` and `port`, adding `/socketcluster/` path automatically. For other clients, you should specify that path. For example, for `ObjectiveC` it would be `self.client.initWithHost("localhost/socketcluster/", onPort: 8000, securely: false)`.

#### 2. Disconnecting and reconnecting

SocketCluster client handles reconnecting for you, but you still might want to know when the connection is established, or when it failed to connect.

##### JavaScript

```js
socket.on('connect', (status) => {
  // Here will come the next step
});
socket.on('disconnect', (code) => {
  console.warn('Socket disconnected with code', code);
});
socket.on('error', (error) => {
  console.warn('Socket error', error);
});
```

##### Python

```py
def onconnect(socket):
  // Here will call the next step

def ondisconnect(socket):
  logging.info("on disconnect got called")

def onConnectError(socket, error):
  logging.info("On connect error got called")

socket.setBasicListener(onconnect, ondisconnect, onConnectError)
```

#### 3. Authorizing and subscribing to the channel of events

We're not providing an authorizing mechanism yet. All you have to do is to emit a `login` event, and you'll get a `channelName` you should subscribe for, and watch for messages and events. Make sure to pass the `master` event, otherwise it should be a monitor, not a client app.

##### JavaScript

```js
socket.emit('login', 'master', (error, channelName) => {
  if (error) {
    console.log(error);
    return;
  }
  channel = socket.subscribe(channelName);
  channel.watch(handleMessages);
  socket.on(channelName, handleMessages);
});

function handleMessages(message) {
  // 5. Listening for monitor events
}
```

##### Python

```py
socket.emitack("login", "master", login)

def login(key, error, channelName):
  socket.subscribe(channelName)
  socket.onchannel(channelName, handleMessages)
  socket.on(channelName, handleMessages)

def handleMessages(key, message):
  // 5. Listening for monitor events
```

You could just emit the `login` event, and omit subscribing (and point `5` bellow) if you want only to log data, not to interact with te app.

#### 4. Sending the action and state to the monitor

To send your data to the monitor use `log` or `log-noid` channel. The latter will add the socket id to the message from the server side (useful when the message was sent before the connection was established).

The message object includes the following:

- `type` - usually should be `ACTION`. If you want to indicate that we're starting a new log (clear all actions emitted before and add `@@INIT`), use `INIT`. In case you have a lifted state similar to one provided by [`redux-devtools-instrument`](https://github.com/zalmoxisus/redux-devtools-instrument), use `STATE`.
- `action` - the action object. It is recommended to lift it in another object, and add `timestamp` to show when the action was fired off: `{ timestamp: Date.now(), action: { type: 'SOME_ACTION' } }`.
- `payload` - usually the state or lifted state object.
- `name` - name of the instance to be shown in the instances selector. If not provided, it will be equal to `instanceId`.
- `instanceId` - an id to identify the instance. If not provided, it will be the same as `id`. However, it is useful when having several instances (or stores) in the same connection. Also if the user will specify a constant value, it would allow to persist the state on app reload.
- `id` - socket connection id, which should be either `socket.id` or should not provided and use `log-noid` channel.

##### JavaScript

```js
const message = {
  type: 'ACTION',
  action: { action, timestamp: Date.now() },
  payload: state,
  id: socket.id,
  instanceId: window.btoa(location.href),
  name: document.title,
};
socket.emit(socket.id ? 'log' : 'log-noid', message);
```

##### Python

```py
class Message:
  def __init__(self, action, state):
    self.type = "ACTION"
    self.action = action
    self.payload = state
    id: socket.id
socket.emit(socket.id if "log" else "log-noid", Message(action, state));
```

#### 5. Listening for monitor events

When a monitor action is emitted, you'll get an event on the subscribed function. The argument object includes a `type` key, which can be:

- `DISPATCH` - a monitor action dispatched on Redux DevTools monitor, like `{ type: 'DISPATCH', payload: { type: 'JUMP_TO_STATE', 'index': 2 }`. See [`redux-devtools-instrument`](https://github.com/zalmoxisus/redux-devtools-instrument/blob/master/src/instrument.js) for details. Additionally to that API, you'll get also a stringified `state` object when needed. So, for example, for time travelling (`JUMP_TO_STATE`) you can just parse and set the state (see the example). Usually implementing this type of actions would be enough.
- `ACTION` - the user requested to dispatch an action remotely like `{ type: 'ACTION', action: '{ type: \'INCREMENT_COUNTER\' }' }`. The `action` can be either a stringified javascript object which should be evalled or a function which arguments should be evalled like [here](https://github.com/zalmoxisus/remotedev-utils/blob/master/src/index.js#L62-L70).
- `START` - a monitor was opened. You could handle this event in order not to do extra tasks when the app is not monitored.
- `STOP` - a monitor was closed. You can take this as no need to send data to the monitor. I there are several monitors and one was closed, all others will send `START` event to acknowledge that we still have to send data.

See [`mobx-remotedev`](https://github.com/zalmoxisus/mobx-remotedev/blob/master/src/monitorActions.js) for an example of implementation without [`redux-devtools-instrument`](https://github.com/zalmoxisus/redux-devtools-instrument/blob/master/src/instrument.js).

##### JavaScript

```js
function handleMessages(message) {
  if (message.type === 'DISPATCH' && message.payload.type === 'JUMP_TO_STATE') {
    store.setState(JSON.parse(message.state));
  }
}
```

##### Python

```py
def handleMessages(key, message):
  if message.type === "DISPATCH" and message.payload.type === "JUMP_TO_STATE":
    store.setState(json.loads(message.state));
```


text:
package org.deeplearning4j.spark.api;

/**
 * Enumeration that is used for specifying the behaviour of repartitioning in {@link org.deeplearning4j.spark.impl.paramavg.ParameterAveragingTrainingMaster}
 * (and possibly elsewhere.
 *
 * "Never" and "Always" repartition options are as expected; the "NumPartitionsWorkersDiffers" will repartition data if and only
 * if the number of partitions is not equal to the number of workers (total cores). Note however that even if the number of partitions
 * and number of workers differ, this does <i>not</i> guarantee that those partitions are balanced (in terms of number of
 * elements) in any way.
 *
 * @author Alex Black
 */
public enum Repartition {
    Never,
    Always,
    NumPartitionsWorkersDiffers
}

redpajama_set_name: RedPajamaGithub


text:
class EmbedNewWordMeaning
  include Mongoid::Document
  include MeaningLike
  field :pos, type: String

  embedded_in :propose_new_wordset

  field :reason, type: String

  validates :reason,
            :length => {minimum: 10},
            :presence => true

  def wordnet?
    propose_new_wordset.wordnet?
  end

  def has_label?(label_name)
    self.labels.where(id: Label.where(name: label_name).first.try(:id)).any?
  end
end


text:
package org.marketcetera.photon.commons.ui.databinding;

import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.databinding.observable.IObservableCollection;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.MultiValidator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.ISWTObservable;
import org.eclipse.jface.databinding.viewers.IViewerObservable;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.databinding.fieldassist.ControlDecorationSupport;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.marketcetera.photon.commons.Validate;
import org.marketcetera.photon.commons.ui.CommonsUI;
import org.marketcetera.photon.commons.ui.databinding.DataBindingUtils.CaptureUpdater;
import org.marketcetera.util.misc.ClassVersion;

/* $License$ */

/**
 * Support class for decorating fields that are required. See
 * {@link #initFor(DataBindingContext, IObservable, String, boolean, Binding)}
 * for use cases.
 *
 * @author Will Horn
 * @version $Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $
 * @since 2.0.0
 */
@ClassVersion("$Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $")
public final class RequiredFieldSupport {

    /**
     * Initialized required field UI for the given target observable. Equivalent
     * to
     * {@link #initFor(DataBindingContext, IObservable, String, boolean, int, Binding)}
     * except the position is defaulted to SWT.TOP | SWT.LEFT (the decoration is
     * positioned at the top left of the control).
     *
     *
     * @param context
     *            the databinding context that manages validation status
     * @param target
     *            the observable to validate and decorate
     * @param description
     *            a description of the observable (for error messages)
     * @param showRequiredDecoration
     *            controls whether a decoration (black asterisk) should be shown
     *            when a required field is missing
     * @param binding
     *            a binding that also contributes validation status, can be null
     * @throws IllegalArgumentException
     *             if context, target, or description is null
     * @throws IllegalStateException
     *             if the context validation realm or the target realm is not
     *             {@link Realm#isCurrent() current}
     */
    public static void initFor(DataBindingContext context, IObservable target,
            String description, boolean showRequiredDecoration, Binding binding) {
        initFor(context, target, description, showRequiredDecoration, SWT.TOP
                | SWT.LEFT, binding);
    }

    /**
     * Initialized required field UI for the given target observable. Two use
     * cases are supported:
     *

     *
String based {@link IObservableValue} - when the String value is the
     * empty string (""), an error status with a message such as
     * "<description> is required" will be generated.

     *
{@link IObservableCollection} - when the collection is empty, an
     * error status with a message such as "At least one <description> must
     * be selected" will be generated.

     *

     * The actual text of the error is subject to localization.
     *

     * In both cases, if the observable is an {@link ISWTObservable} or
     * {@link IViewerObservable} (or decoration thereof), and if
     * showRequiredDecoration is true, then when the error status is generated,
     * a {@link ControlDecoration} will be added to the observable's control.
     * The decoration will display the
     * {@link FieldDecorationRegistry#DEC_REQUIRED} (black asterisk) icon with
     * the error message as the icon tooltip. The decoration will be positioned
     * according to controlDecorationPosition and will be accessible from the
     * control using
     * control.getData(DataBindingUtils.CONTROL_DECORATION).
     *

     * If the optional binding is provided, the binding status will be queried
     * first and the required field validation will only kick in when the
     * binding is ok.
     *
     * @param context
     *            the databinding context that manages validation status
     * @param target
     *            the observable to validate and decorate
     * @param description
     *            a description of the observable (for error messages)
     * @param showRequiredDecoration
     *            controls whether a decoration (black asterisk) should be shown
     *            when a required field is missing
     * @param controlDecorationPosition
     *            the position of the control decoration, e.g. SWT.TOP |
     *            SWT.LEFT
     * @param binding
     *            a binding that also contributes validation status, can be null
     * @throws IllegalArgumentException
     *             if context, target, or description is null
     * @throws IllegalStateException
     *             if the context validation realm or the target realm is not
     *             {@link Realm#isCurrent() current}
     */
    public static void initFor(DataBindingContext context, IObservable target,
            String description, boolean showRequiredDecoration,
            int controlDecorationPosition, Binding binding) {
        Validate.notNull(context, "context", //$NON-NLS-1$
                target, "target", //$NON-NLS-1$
                description, "description"); //$NON-NLS-1$
        if (!context.getValidationRealm().isCurrent()) {
            throw new IllegalStateException(
                    "must be called from the validation realm of context"); //$NON-NLS-1$
        }
        if (!target.getRealm().isCurrent()) {
            throw new IllegalStateException(
                    "must be called from the realm of target"); //$NON-NLS-1$
        }
        MultiValidator validator = new RequiredFieldValidator(target,
                description, binding);
        context.addValidationStatusProvider(validator);
        ControlDecorationSupport.create(validator, SWT.LEFT | SWT.TOP, null,
                showRequiredDecoration ? new RequiredDecorationUpdater()
                        : new HideRequiredUpdater());
    }

    /**
     * Updates control decorations. If the status is {@link RequiredStatus},
     * {@link FieldDecorationRegistry#DEC_REQUIRED} will be used for the icon
     * instead of {@link FieldDecorationRegistry#DEC_ERROR}.
     */
    @ClassVersion("$Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $")
    private static final class RequiredDecorationUpdater extends CaptureUpdater {

        @Override
        protected Image getImage(IStatus status) {
            if (status instanceof RequiredStatus) {
                return FieldDecorationRegistry.getDefault().getFieldDecoration(
                        FieldDecorationRegistry.DEC_REQUIRED).getImage();
            }
            return super.getImage(status);
        }
    }

    /**
     * Updates control decorations. If the status is {@link RequiredStatus}, the
     * decoration is hidden.
     */
    @ClassVersion("$Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $")
    private static final class HideRequiredUpdater extends CaptureUpdater {

        @Override
        protected Image getImage(IStatus status) {
            if (status instanceof RequiredStatus) {
                return null;
            }
            return super.getImage(status);
        }
    }

    /**
     * A custom status for indicating a required field is missing.
     */
    @ClassVersion("$Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $")
    public static class RequiredStatus extends Status {

        /**
         * Constructor.
         *
         * @param message
         *            a human-readable message, localized to the current locale
         */
        public RequiredStatus(String message) {
            super(IStatus.ERROR, CommonsUI.PLUGIN_ID, 0, message, null);
        }
    }

    /**
     * Validates required fields. For {@link IObservableValue}, it validates
     * that the value is not null and not an empty string. For
     * {@link IObservableCollection}, it validates that the collection is not
     * empty.
     *

     * If a binding is provided, the binding status will be queried first and
     * the required field validation will only kick in when the binding is ok.
     */
    @ClassVersion("$Id: RequiredFieldSupport.java 16841 2014-02-20 19:59:04Z colin $")
    private static final class RequiredFieldValidator extends MultiValidator {
        private final IObservable mTargetObservable;
        private final String mDescription;
        private final Binding mBinding;

        /**
         * Constructor.
         *
         * @param observable
         *            the observable to validate
         * @param description
         *            the description of the field for error messages
         * @param binding
         *            a binding that also contributes validation status, can be
         *            null
         * @throws IllegalArgumentException
         *             if observable or description is null
         */
        public RequiredFieldValidator(IObservable observable,
                String description, Binding binding) {
            Validate.notNull(observable, "observable", //$NON-NLS-1$
                    description, "description"); //$NON-NLS-1$
            mTargetObservable = observable;
            mDescription = description;
            mBinding = binding;
        }

        @Override
        protected IStatus validate() {
            // first query observables to ensure they are tracked
            String message = null;
            if (mTargetObservable instanceof IObservableValue) {
                final Object value = ((IObservableValue) mTargetObservable)
                        .getValue();
                if (value == null || String.valueOf(value).isEmpty()) {
                    message = Messages.REQUIRED_FIELD_SUPPORT_MISSING_VALUE
                            .getText(mDescription);
                }
            } else if (mTargetObservable instanceof IObservableCollection) {
                if (((IObservableCollection) mTargetObservable).isEmpty()) {
                    message = Messages.REQUIRED_FIELD_SUPPORT_MISSING_COLLECTION
                            .getText(mDescription);
                }
            }
            // even if the field is missing, prefer the binding status
            if (mBinding != null) {
                final IStatus status = (IStatus) mBinding.getValidationStatus()
                        .getValue();
                if (!status.isOK()) {
                    return status;
                }
            }
            // binding is null or its status is ok so return result of
            // observable validation
            if (message == null) {
                return Status.OK_STATUS;
            } else {
                return new RequiredStatus(message);
            }
        }
    }
}


text:
package netlib

import (
	"fmt"
	"reflect"
)

var handlers = make(map[int]Handler)

type Handler interface {
	Process(session *Session, packetid int, data interface{}) error
}

type HandlerWrapper func(session *Session, packetid int, data interface{}) error

func (hw HandlerWrapper) Process(session *Session, packetid int, data interface{}) error {
	return hw(session, packetid, data)
}

func RegisterHandler(packetId int, h Handler) {
	if _, ok := handlers[packetId]; ok {
		panic(fmt.Sprintf("repeate register handler: %v Handler type=%v", packetId, reflect.TypeOf(h)))
	}

	handlers[packetId] = h
}

func Register1ToMHandler(h Handler, packetIds ...int) {
	for _, packetId := range packetIds {
		RegisterHandler(packetId, h)
	}
}

func RegisterRangeHandler(start, end int, h Handler) {
	for ; start <= end; start++ {
		RegisterHandler(start, h)
	}
}

func GetHandler(packetId int) Handler {
	if h, ok := handlers[packetId]; ok {
		return h
	}

	return nil
}


text:
<!doctype html>

<meta charset="utf-8">
<title>A selection puzzle that sheds light on human thinking – Casting Out Nines</title>
<meta name="description" content="One of the hardest days of the semester in my view is the first day. It's difficult to plan. I'm not a big icebreaker guy because I don't care for small talk. I think it's wasteful to go over the syllabus (make a video instead). But I also don't like jumping right into the course material because the enrollment in the class is in flux, and people who join the class later will get behind. So I want to do something with students that motivates the big ideas of the course and gets them engaged with each other. Those are hard to come up with.

">
<meta name="keywords" content="teaching">

<meta name="twitter:title" content="A selection puzzle that sheds light on human thinking">
<meta name="twitter:description" content="One of the hardest days of the semester in my view is the first day. It's difficult to plan. I'm not a big icebreaker guy because I don't care for small talk. I think it's wasteful to go over the syllabus (make a video instead). But I also don't like jumping right into the course material because the enrollment in the class is in flux, and people who join the class later will get behind. So I want to do something with students that motivates the big ideas of the course and gets them engaged with each other. Those are hard to come up with.

">
<meta name="twitter:site" content="@RobertTalbert">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/blog/images/site-logo.png">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="A selection puzzle that sheds light on human thinking">
<meta property="og:description" content="One of the hardest days of the semester in my view is the first day. It's difficult to plan. I'm not a big icebreaker guy because I don't care for small talk. I think it's wasteful to go over the syllabus (make a video instead). But I also don't like jumping right into the course material because the enrollment in the class is in flux, and people who join the class later will get behind. So I want to do something with students that motivates the big ideas of the course and gets them engaged with each other. Those are hard to come up with.

">
<meta property="og:url" content="/blog/2015/quick-puzzle">
<meta property="og:site_name" content="Casting Out Nines">

<link rel="canonical" href="/blog/2015/quick-puzzle">
<link href="/blog/feed.xml" type="application/atom+xml" rel="alternate" title="Casting Out Nines Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/blog/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/blog/favicon.ico">

<link rel="shortcut icon" href="/blog/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/blog/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/blog/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/blog/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/blog/images/apple-touch-icon-144x144-precomposed.png">

About

Search

RT

Casting Out Nines

math ∩ tech ∩ edu

teaching

A selection puzzle that sheds light on human thinking

        By
        <time datetime="2015-09-03T13:27:11-04:00"> September 03, 2015</time>

         Comment

One of the hardest days of the semester in my view is the first day. It's difficult to plan. I'm not a big icebreaker guy because I don't care for small talk. I think it's wasteful to go over the syllabus (make a video instead). But I also don't like jumping right into the course material because the enrollment in the class is in flux, and people who join the class later will get behind. So I want to do something with students that motivates the big ideas of the course and gets them engaged with each other. Those are hard to come up with.

Fortunately, this past summer a former student of mine emailed me an article that had an idea that from the moment I saw it, I knew I wanted to try it during the first couple of days of my three Discrete Structures for Computer Science courses this fall (which started on Monday). This is a two-semester sequence, and I'm teaching two sections of the first semester and on section of the second.

The activity comes in two parts.

Part 1

Below are four cards lying flat on a table. Each card has a single-digit number on one side and one of two colors (blue or green) on the other side. The first and second cards you see show a 5 and an 8. The third and fourth cards are blue and green respectively.

Now consider the following statement:

If a card shows an even number on one face, then its opposite face is blue.

Question: Which cards must you turn over in order to test the truth of this statement, without turning over any unnecessary cards?

Students were seated at square tables in groups of 4 and had the above on a sheet of paper along with a 4x4 grid with all 16 possible choices for which cards to turn over. I gave them three minutes to think about this task silently to themselves, and then they marked the box in the grid with their choice. I collected these and tallied up the class' responses while they went on to Part 2.

Part 2

Now suppose you're a police officer in a bar1 looking for underage drinkers. The rule you are following is:

If a person is drinking beer, then that person must be over 21.

You see four people, and through prior investigation you know the following information about each of those four people:

Question: Which people do you need to check to make sure the rule is being followed?

Again, I gave the students three minutes to make their choices before we moved on to the discussion and debrief.

The Results and Discussion

When the three minutes were up, I let them talk about their reasoning with each other while I tallied up all the responses from the class to the number/color card question. Those responses were all over the place. In the first semester courses (both sections) there was a wide spread of responses covering about 2/3 of the possible choices, and nowhere near a majority on any one item. Only 5 people (out of 30) voted for the correct answer in one section and only 7 in the other (also out of 30). In the second semester course, the responses were a lot more uniform – 15 out of 32 voting for the right answer, and the other 17 spread over only 3-4 different responses. In either case though — the majority of students were not getting the correct response. And in the full class discussion, even when a student was able to explain his reasoning clearly, other students seemed skeptical.

But when we switched to the underage drinking question, it was like night and day. In the first semester courses between 75% and 85% of the students were getting the right answer; in the second-semester course it was nearly everyone. And they were able to explain their reasoning with ease – in fact they thought the right answer was obvious and needed no explanation.

The Punchline

The punchline, of course, is that these two problems are exactly the same except for the context. The "right answers" are even given in the same positions in the graphics. And yet the differences lead to quite different results, and give some very interesting insights into how we think and what we need to think more clearly.

Of course, I didn't make this activity up. This is a classic psychology experiment known as the Wason selection task. When Peter Wason ran this experiment, 90% of his subjects responded incorrectly to the number/card version of the task. Not only this, when shown the correct responses, his subjects said that they would choose the same cards again if asked. This led Wason and subsequent researchers to theorize that the human brain tends to cut corners when confronted with an abstract task — which should come as a surprise to nobody, but it has serious implications for students wanting to become mathematicians, statisticians, or computer scientists like my students.

The underage drinking version of the task was made later, in 1982 by psychologists Richard Griggs and James Cox. In their study, 75% of the subjects chose the correct response. The same logical rule underlies both versions of the task, but when put into a familiar context, the brain becomes much better at applying this rule.

I told the students that this activity highlights at least three things.

It highlights the need for structures – hence the name of the course – to help us reason clearly about abstractions. I think it's no coincidence that the second-semester students, who studied logic during the first semester of the course and who have generally a lot of experience applying logic to engineering and programming, showed higher success rates on the card version. They have a structure that supports their brains when it wants to cut corners.

It strongly highlights the importance of context when dealing with abstraction. Yes, we need to study the mathematics in the course on its terms, with proper notation and whatnot. But the results of the task, and of the psychologists' studies, strongly suggests that we will make a lot more meaning out of the mathematics if we couch it in familiar terms.

More technically, it illustrates a common problem-solving technique especially prevalent in discrete mathematics, which is to map the current problem onto a more familiar one, solve the more familiar one, and then map it back.

Personally, this experiment also reminds me that mathematics often has as much do to with psychology as it does with logic. For example, deciding whether a theorem has been proven usually is the result of a process of persuasion, rather than as the outcome of an emotionless calculation. We don't typically decide that mathematics is correct against our wills. So it's smart to pay attention to the human element when writing mathematics or writing code.

Finally, this is a fun exercise to turn into a recurring character in the course. The next time students want to believe that the converse of a conditional statement is equivalent to the statement, I'll ask them: If I see a person who is over 21, should I arrest him if he's not drinking?

PS: I never told you the answers. Discuss in the comments.

There was some discussion here among some of my friends because in some places, people who are underage are not even allowed into bars. We're assuming that they are. ↩

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

        Previous

        Next

© 2016 Robert Talbert. Powered by Jekyll using the So Simple Theme.


text:
package org.asteriskjava.manager.action;

import org.asteriskjava.manager.event.AgentsCompleteEvent;
import org.asteriskjava.manager.event.ResponseEvent;

/**
 * The AgentsAction requests the state of all agents.

 * For each agent an AgentsEvent is generated. After the state of all agents has been
 * reported an AgentsCompleteEvent is generated.

 * Available since Asterisk 1.2
 *
 * @see org.asteriskjava.manager.event.AgentsEvent
 * @see org.asteriskjava.manager.event.AgentsCompleteEvent
 *
 * @author srt
 * @version $Id$
 * @since 0.2
 */
public class AgentsAction extends AbstractManagerAction implements EventGeneratingAction
{
    /**
     * Serializable version identifier
     */
    static final long serialVersionUID = -320228893513973367L;

    /**
     * Creates a new AgentsAction.
     */
    public AgentsAction()
    {

    }

    /**
     * Returns the name of this action, i.e. "Agents".
     */
    @Override
   public String getAction()
    {
        return "Agents";
    }

   public Class<? extends ResponseEvent> getActionCompleteEventClass()
    {
        return AgentsCompleteEvent.class;
    }
}


text:
"""
:codeauthor: Shane Lee <slee@saltstack.com>
"""
import os

import pytest

import salt.modules.cmdmod as cmdmod
import salt.modules.win_file as win_file
import salt.modules.win_lgpo as win_lgpo
import salt.utils.win_dacl as win_dacl
import salt.utils.win_lgpo_auditpol as win_lgpo_auditpol
import salt.utils.win_reg as win_reg
from tests.support.mock import patch

pytestmark = [
    pytest.mark.windows_whitelisted,
    pytest.mark.skip_unless_on_windows,
]

@pytest.fixture
def configure_loader_modules(tmp_path):
    cachedir = tmp_path / "__test_admx_policy_cache_dir"
    cachedir.mkdir(parents=True, exist_ok=True)
    return {
        win_lgpo: {
            "__salt__": {
                "cmd.run": cmdmod.run,
                "file.file_exists": win_file.file_exists,
                "file.makedirs": win_file.makedirs_,
                "file.remove": win_file.remove,
                "file.write": win_file.write,
            },
            "__opts__": {
                "cachedir": str(cachedir),
            },
            "__utils__": {
                "auditpol.get_auditpol_dump": win_lgpo_auditpol.get_auditpol_dump,
                "reg.read_value": win_reg.read_value,
            },
        },
        win_file: {
            "__utils__": {
                "dacl.set_perms": win_dacl.set_perms,
            },
        },
    }

def _test_mechanism(policy_name):
    """
    Helper function to get current setting
    """
    policy_data = win_lgpo._policy_info()
    policy_definition = policy_data.policies["Machine"]["policies"][policy_name]
    return win_lgpo._get_policy_info_setting(policy_definition)

def test_registry():
    """
    Test getting policy value using the Registry mechanism
    """
    policy_name = "RemoteRegistryExactPaths"
    result = _test_mechanism(policy_name=policy_name)
    expected = [
        "System\\CurrentControlSet\\Control\\ProductOptions",
        "System\\CurrentControlSet\\Control\\Server Applications",
        "Software\\Microsoft\\Windows NT\\CurrentVersion",
    ]
    assert result == expected

def test_secedit():
    """
    Test getting policy value using the Secedit mechanism
    """
    policy_name = "LSAAnonymousNameLookup"
    result = _test_mechanism(policy_name=policy_name)
    expected = "Disabled"
    assert result == expected

def test_netsh():
    """
    Test getting the policy value using the NetSH mechanism
    """
    policy_name = "WfwDomainState"
    all_settings = {
        "State": "NotConfigured",
        "Inbound": "NotConfigured",
        "Outbound": "NotConfigured",
        "LocalFirewallRules": "NotConfigured",
        "LocalConSecRules": "NotConfigured",
        "InboundUserNotification": "NotConfigured",
        "RemoteManagement": "NotConfigured",
        "UnicastResponseToMulticast": "NotConfigured",
        "LogAllowedConnections": "NotConfigured",
        "LogDroppedConnections": "NotConfigured",
        "FileName": "NotConfigured",
        "MaxFileSize": "NotConfigured",
    }
    with patch("salt.utils.win_lgpo_netsh.get_all_settings", return_value=all_settings):
        result = _test_mechanism(policy_name=policy_name)
    expected = "Not configured"
    assert result == expected

@pytest.mark.destructive_test
def test_adv_audit():
    """
    Test getting the policy value using the AdvAudit mechanism
    """
    system_root = os.environ.get("SystemRoot", "C:\\Windows")
    f_audit = os.path.join(system_root, "security", "audit", "audit.csv")
    f_audit_gpo = os.path.join(
        system_root,
        "System32",
        "GroupPolicy",
        "Machine",
        "Microsoft",
        "Windows NT",
        "Audit",
        "audit.csv",
    )
    if os.path.exists(f_audit):
        os.remove(f_audit)
    if os.path.exists(f_audit_gpo):
        os.remove(f_audit_gpo)
    policy_name = "AuditCredentialValidation"
    result = _test_mechanism(policy_name=policy_name)
    expected = "Not Configured"
    assert result == expected

def test_net_user_modal():
    """
    Test getting the policy value using the NetUserModal mechanism
    """
    policy_name = "PasswordHistory"
    result = _test_mechanism(policy_name=policy_name)
    expected = 0
    assert result == expected

def test_lsa_rights():
    """
    Test getting the policy value using the LsaRights mechanism
    """
    policy_name = "SeTrustedCredManAccessPrivilege"
    result = _test_mechanism(policy_name=policy_name)
    expected = []
    assert result == expected

def test_script_ini():
    """
    Test getting the policy value using the ScriptIni value
    """
    policy_name = "StartupScripts"
    result = _test_mechanism(policy_name=policy_name)
    expected = None
    assert result == expected


text:
/*
 * Original based on lift-mongodb-record
 * And lift-record
 */

package net.indoorlabs.neo4j

import org.neo4j.kernel.EmbeddedGraphDatabase
import java.util.concurrent.ConcurrentHashMap
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.graphdb.factory.GraphDatabaseFactory

/*
* A trait for identfying Neo4J instances
*/
trait Neo4jIdentifier {
  def jndiName: String
  override def toString() = "Neo4jIdentifier("+jndiName+")"
  override def hashCode() = jndiName.hashCode()
  override def equals(other: Any): Boolean = other match {
    case mi: Neo4jIdentifier => mi.jndiName == this.jndiName
    case _ => false
  }
}

/*
* The default Neo4JIdentifier
*/
case object DefaultNeo4jIdentifier extends Neo4jIdentifier {
  val jndiName = "test"
}

/*
* Wrapper for getting a reference to a db from the given Neo4J instance
*/
case class Neo4jAddress(host: Neo4jHostBase) {
  def db = host.neo4j
}

/*
* Wrapper for creating a GraphDB instance
*/
abstract class Neo4jHostBase {
  def neo4j: GraphDatabaseService
}

case class Neo4jHost(storeDir: String = "tmp/default-graphDb", options: Map[String, String] = Map[String, String]()) extends Neo4jHostBase {
  import scala.collection.JavaConversions._
  override lazy val neo4j = {
    val opts = options + ("allow_store_upgrade" -> "true")
    new GraphDatabaseFactory()
            .newEmbeddedDatabaseBuilder( storeDir )
            .setConfig( opts )
            .newGraphDatabase()
    //new EmbeddedGraphDatabase(storeDir, opts)

    //if (options.size > 0) new EmbeddedGraphDatabase(storeDir, options)
    //                        else new EmbeddedGraphDatabase(storeDir)
  }
}
object Neo4jHost {
  def apply(stDir: String): Neo4jHost =  Neo4jHost(storeDir=stDir)
  def apply(opt: Map[String, String]): Neo4jHost = Neo4jHost(options=opt)
}

/*
/*
* Wrapper for creating a Replica Pair
*/
case class MongoPair(left: ServerAddress, right: ServerAddress, options: MongoOptions = new MongoOptions) extends MongoHostBase {
  lazy val mongo = new Mongo(left, right, options)
}

/*
 * Wrapper for creating a Replica Set
 */
case class MongoSet(dbs: List[ServerAddress], options: MongoOptions = new MongoOptions) extends MongoHostBase {
  import scala.collection.JavaConversions._
  lazy val mongo = new Mongo(dbs, options)
}
*/

/*
* Main Neo4j object
*/
object Neo4jDB {

  /*
  * HashMap of Neo4jAddresses, keyed by Neo4jIdentifier
  */
  private val dbs = new ConcurrentHashMap[Neo4jIdentifier, Neo4jAddress]

  /*
  * Define a Neo4j
  */
  def defineDb(name: Neo4jIdentifier, address: Neo4jAddress) {
    dbs.put(name, address)
  }
  /*
   * Define a Mongo db using a standard Mongo instance.
   */
  def defineDb(name: Neo4jIdentifier, n4j: GraphDatabaseService) {
    dbs.put(name, Neo4jAddress(new Neo4jHostBase { override def neo4j = n4j }))
  }

  /*
  * Get a DB reference
  */
  def getDb(name: Neo4jIdentifier): Option[GraphDatabaseService] = dbs.get(name) match {
    case null => None
    case na: Neo4jAddress => Some(na.db)
  }

  def use[T](name: Neo4jIdentifier)(f: (GraphDatabaseService) => T): T = {

    val db = getDb(name) match {
      case Some(neo4j) => neo4j
      case _ => throw new Exception("Neo4j not found: "+name.toString)
    }

    f(db)
  }

  def use[T](f: (GraphDatabaseService) => T): T = {

    val db = getDb(DefaultNeo4jIdentifier) match {
      case Some(neo4j) => neo4j
      case _ => throw new Exception("Neo4j not found: "+DefaultNeo4jIdentifier.toString)
    }

    f(db)
  }

  //
  def close {
    import scala.collection.JavaConversions._
    dbs.foreach(_._2.db.shutdown())
    dbs.clear
  }
}


text:
package org.jayware.e2.component.api;

public class MalformedComponentException
extends RuntimeException
{
    public MalformedComponentException(String message)
    {
        super(message);
    }

    public MalformedComponentException(String message, Throwable cause)
    {
        super(message, cause);
    }
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\PhpUnit;

use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Gert de Pagter <BackEndTea@gmail.com>
 */
final class PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'All PHPUnit test classes should be marked as internal.',
            [
                new CodeSample("<?php\nclass MyTest extends TestCase {}\n"),
                new CodeSample(
                    "<?php\nclass MyTest extends TestCase {}\nfinal class FinalTest extends TestCase {}\nabstract class AbstractTest extends TestCase {}\n",
                    ['types' => ['final']]
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     *
     * Must run before FinalInternalClassFixer.
     */
    public function getPriority()
    {
        return 68;
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition()
    {
        $types = ['normal', 'final', 'abstract'];

        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('types', 'What types of classes to mark as internal'))
                ->setAllowedValues([(new AllowedValueSubset($types))])
                ->setAllowedTypes(['array'])
                ->setDefault(['normal', 'final'])
                ->getOption(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex)
    {
        $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]);

        if (!$this->isAllowedByConfiguration($tokens, $classIndex)) {
            return;
        }

        $docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex);

        if ($this->isPHPDoc($tokens, $docBlockIndex)) {
            $this->updateDocBlockIfNeeded($tokens, $docBlockIndex);
        } else {
            $this->createDocBlock($tokens, $docBlockIndex);
        }
    }

    /**
     * @param int $i
     *
     * @return bool
     */
    private function isAllowedByConfiguration(Tokens $tokens, $i)
    {
        $typeIndex = $tokens->getPrevMeaningfulToken($i);
        if ($tokens[$typeIndex]->isGivenKind(T_FINAL)) {
            return \in_array('final', $this->configuration['types'], true);
        }

        if ($tokens[$typeIndex]->isGivenKind(T_ABSTRACT)) {
            return \in_array('abstract', $this->configuration['types'], true);
        }

        return \in_array('normal', $this->configuration['types'], true);
    }

    private function createDocBlock(Tokens $tokens, $docBlockIndex)
    {
        $lineEnd = $this->whitespacesConfig->getLineEnding();
        $originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
        $toInsert = [
            new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @internal".$lineEnd."{$originalIndent} */"]),
            new Token([T_WHITESPACE, $lineEnd.$originalIndent]),
        ];
        $index = $tokens->getNextMeaningfulToken($docBlockIndex);
        $tokens->insertAt($index, $toInsert);
    }

    private function updateDocBlockIfNeeded(Tokens $tokens, $docBlockIndex)
    {
        $doc = new DocBlock($tokens[$docBlockIndex]->getContent());
        if (!empty($doc->getAnnotationsOfType('internal'))) {
            return;
        }
        $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex);
        $lines = $this->addInternalAnnotation($doc, $tokens, $docBlockIndex);
        $lines = implode('', $lines);

        $tokens[$docBlockIndex] = new Token([T_DOC_COMMENT, $lines]);
    }

    /**
     * @param int $index
     *
     * @return string
     */
    private function detectIndent(Tokens $tokens, $index)
    {
        if (!$tokens[$index - 1]->isWhitespace()) {
            return ''; // cannot detect indent
        }

        $explodedContent = explode($this->whitespacesConfig->getLineEnding(), $tokens[$index - 1]->getContent());

        return end($explodedContent);
    }

    /**
     * @param int $docBlockIndex
     *
     * @return Line[]
     */
    private function addInternalAnnotation(DocBlock $docBlock, Tokens $tokens, $docBlockIndex)
    {
        $lines = $docBlock->getLines();
        $originalIndent = $this->detectIndent($tokens, $docBlockIndex);
        $lineEnd = $this->whitespacesConfig->getLineEnding();
        array_splice($lines, -1, 0, $originalIndent.' *'.$lineEnd.$originalIndent.' * @internal'.$lineEnd);

        return $lines;
    }

    /**
     * @param int $docBlockIndex
     *
     * @return DocBlock
     */
    private function makeDocBlockMultiLineIfNeeded(DocBlock $doc, Tokens $tokens, $docBlockIndex)
    {
        $lines = $doc->getLines();
        if (1 === \count($lines) && empty($doc->getAnnotationsOfType('internal'))) {
            $indent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
            $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding());

            return $doc;
        }

        return $doc;
    }
}


text:
<?php

namespace Concrete\Package\Concrete5DoctrineBehavioralExtensions;

use Concrete\Core\Package\Package;
use Concrete\Core\Package\PackageService;
use Concrete\Core\Page\Single;
use Doctrine\ORM\ORMException;
use Kaapiii\Doctrine\BehavioralExtensions\ListenerController;
use Kaapiii\Doctrine\BehavioralExtensions\InstallationManager;

/**
 * Package controller
 *
 * @author Markus Liechti <markus@liechti.io>
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
class Controller extends Package
{
    const CUSTOM_NAMESPACE = '\Kaapiii\Doctrine\BehavioralExtensions';

    /**
     * @var string
     */
    protected $pkgHandle  = 'concrete5_doctrine_behavioral_extensions';

    /**
     * @var string
     */
    protected $appVersionRequired = '8.5.0';

    /**
     * @var string
     */
    protected $pkgVersion         = '2.0.0';

    /**
     * Register the custom namespace
     *
     * @var array
     */
    protected $pkgAutoloaderRegistries = array(
        'src/Kaapiii/Doctrine/BehavioralExtensions' => self::CUSTOM_NAMESPACE,
    );

    /**
     * @return string
     */
    public function getPackageDescription()
    {
        return t('Package add support for Doctrine2 behavioral extensions aka (Gedmo Extensions)');
    }

    /**
     * @return string
     */
    public function getPackageName()
    {
        return t('Doctrine2 behavioral extensions');
    }

    /**
     * @return \Concrete\Core\Entity\Package|void
     */
    public function install()
    {
        $this->registerPackageVendorAutoload();
        $installationManager = new InstallationManager($this->app);
        $installationManager->installComponents();
        $pkg = parent::install();
        Single::add('/dashboard/system/doctrine_behavioral_extensions', $pkg);
        $this->installConfig();
    }

    /**
     * @throws ORMException
     */
    public function on_start()
    {
        $this->registerPackageVendorAutoload();
        $listenerCtrl = new ListenerController($this->app, $this->getConfig());
        $listenerCtrl->registerDoctrineBehavioralExtensions();
    }

    /**
     * Upgrade logic
     */
    public function upgrade()
    {
        parent::upgrade();

        /** @var \Concrete\Core\Entity\Package $packageEntity */
        $packageEntity = $this->app->make(PackageService::class)->getByHandle($this->pkgHandle);
        $version = $packageEntity->getPackageVersion();

        /**
         * Only Upgrade if installed package version was <= 1.0.2
         */
        if (version_compare($version, '1.0.2', '>')) {
            $this->switchFromFileConfigToDbConfig();
        }

        /**
         * Only run if upgrading to version 2.0.0 from <=1.1.0
         */
        if (version_compare($version, '1.1.0', '>')) {
            $this->updateActivateSoftDeletable();
        }
    }

    /**
     * Uninstall logic
     */
    public function uninstall()
    {
        $this->registerPackageVendorAutoload();
        $installationManager = new InstallationManager($this->app);
        $installationManager->uninstallComponents();
        parent::uninstall();
    }

    /**
     * Register the autoloader
     * Note: By wrapping the autoloader include call in a file_exists
     * function, the package installation will also work by adding it
     * to the projects composer.json
     */
    protected function registerPackageVendorAutoload()
    {
        if (file_exists($this->getPackagePath().'/vendor/autoload.php')) {
            require $this->getPackagePath().'/vendor/autoload.php';
        }
    }

    /**
     * Set the package config
     */
    protected function installConfig()
    {
        $config = $this->getConfig();
        $config->save('settings.sluggable.active', true);
        $config->save('settings.sluggable.transliterator', ListenerController::DEFAULT_TRANSLITERATOR);
        $config->save('settings.sluggable.transliteratorMethod', ListenerController::DEFAULT_TRANSLITERATOR_METHOD);

        $config->save('settings.timestampable.active', true);
        $config->save('settings.blameable.active', true);
        $config->save('settings.sortable.active', true);
        $config->save('settings.tree.active', true);
        $config->save('settings.loggable.active', true);
        $config->save('settings.translatable.active', true);
        $config->save('settings.softDeletable.active', true);
    }

    /**
     * Switch from file config to database config
     */
    private function switchFromFileConfigToDbConfig()
    {
        $fileConfig = $this->getFileConfig();

        // Only run if file config exists
        if (!is_object($fileConfig)) {
            return;
        }

        $sluggable = $fileConfig->get('settings.sluggable.active');
        $sluggableTranslit = $fileConfig->get('settings.sluggable.transliterator');
        $sluggableTranslitMethod = $fileConfig->get('settings.sluggable.transliteratorMethod');
        $timestampable = $fileConfig->get('settings.timestampable.active');
        $blameable = $fileConfig->get('settings.blameable.active');
        $sortable = $fileConfig->get('settings.sortable.active');
        $tree = $fileConfig->get('settings.tree.active');
        $loggable = $fileConfig->get('settings.loggable.active');
        $translatable = $fileConfig->get('settings.translatable.active');

        $config = $this->getConfig();
        if (!is_null($sluggable)){
            $config->save('settings.sluggable.active', $sluggable);
        }
        if (!is_null($sluggableTranslit)){
            $config->save('settings.sluggable.transliterator', $sluggableTranslit);
        }
        if (!is_null($sluggableTranslitMethod)){
            $config->save('settings.sluggable.transliteratorMethod', $sluggableTranslitMethod);
        }
        if (!is_null($timestampable)){
            $config->save('settings.timestampable.active', $timestampable);
        }
        if (!is_null($blameable)){
            $config->save('settings.blameable.active', $blameable);
        }
        if (!is_null($sortable)){
            $config->save('settings.sortable.active', $sortable);
        }
        if (!is_null($tree)){
            $config->save('settings.tree.active', $tree);
        }
        if (!is_null($loggable)){
            $config->save('settings.loggable.active', $loggable);
        }
        if (!is_null($translatable)){
            $config->save('settings.translatable.active', $translatable);
        }

        $this->removeConfigFile();
    }

    public function updateActivateSoftDeletable()
    {
        $config = $this->getConfig();
        $config->save('settings.softDeletable.active', 1);
    }

    /**
     * Remove package config file
     */
    public function removeConfigFile()
    {
        $this->app->make('config')->clearNamespace($this->getPackageHandle());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.ContentManagement.Records;

namespace Orchard.Advertise.Models {
    public class AdvertiseHomePartRecord : ContentPartRecord {
    }
}


text:
	<video id="threesixty_photo_video" loop muted width="100%" height="100%">
		<source src="images/video/360_photography.mp4" type="video/mp4">
	</video>

							0%

			<button class="btn btn-lg view-active" id="main_view_button_threeSixtyPhoto" onclick="pause3()">Main View</button>
			<button class="btn btn-lg" id="video_button_threeSixtyPhoto" onclick="play3()">Video</button>

360° Photography

360° photography allows users to examine an object by rotating and tilting the object to provide a full 360° view. This is perfect for couches, tables, and other home good that would be placed in the center of a room. Recommended for products that have one specific color.

ABOUT HOUSE TIPSTER

House Tipster is much more then just another improvment website. House Tipster is the greatest innovation in home renovation. By using groundbreaking technologies, we`ve created the most engaging platform for homeowners and service professionals. House Tipster makes it so you don`t have to work harder, but smarter when designing your home.


text:
cask 'breakaway' do
  version '2.0.1'
  sha256 'df5a3d42558f9cdc778c434f88f7e062032cf33dd751ef01e6109a9848a7f76a'

  # sourceforge.net/project/breakaway was verified as official when first introduced to the cask
  url "http://downloads.sourceforge.net/project/breakaway/breakaway-#{version}.zip"
  name 'Breakaway'
  homepage 'http://mutablecode.com/apps/breakaway.html'
  license :gpl

  app "breakaway-#{version}/Breakaway.app"
end


text:
title: L.esri.ImageMapLayer
layout: documentation.hbs
---

# {{page.data.title}}

Extends [`L.esri.RasterLayer`]({{assets}}api-reference/layers/raster-layer.html)

Render and visualize Image Services from ArcGIS Online and ArcGIS Server.

Image Services provide access to raster data through a web service.

### Constructor

            Constructor
            Description

            L.esri.imageMapLayer({{{param 'Object' 'options'}}})
            The options parameter can accept the same options as L.ImageOverlay. You also must pass a url key in your options.

### Options

`L.esri.ImageMapLayer` also accepts all the options you can pass to [`L.ImageOverlay`](https://leafletjs.com/reference.html#imageoverlay).

Option | Type | Default | Description
--- | --- | --- | ---
`url` | `String` | | *Required* URL of the [Image Service](https://developers.arcgis.com/rest/services-reference/image-service.htm).
`format` | `String` | `'jpegpng'` | Output format of the image.
`f` | `String` | `'image'` | Server response content type [`"json"` | `"image"`](https://developers.arcgis.com/rest/services-reference/export-image.htm).
`opacity` | `Number` | `1` | Opacity of the layer. Should be a value between 0 and 1.
`pane` | `String` | `overlayPane` | The [map pane](https://leafletjs.com/reference.html#map-pane) to render on. This is the preferred technique to control draw order in Leaflet 1.x.
`zIndex` | `Number` | | Used to refine draw order further (within a [map pane](https://leafletjs.com/reference.html#map-pane)).
`position` | `String` | `'front'` | Legacy option to control draw order. For best results, use `pane`.
`maxZoom` | `Number` | | Closest zoom level the layer will be displayed on the map.
`minZoom` | `Number` | | Furthest zoom level the layer will be displayed on the map.
`bandIds` | `String` |   | If there are multiple bands, you can specify which bands to export.
`noData` | `Number` |   | The pixel value representing no information.
`noDataInterpretation` | `String` |   | Interpretation of the `noData` setting.
`pixelType` | `String` |   | Leave `pixelType` as unspecified, or `UNKNOWN`, in most exportImage use cases, unless such `pixelType` is desired. Possible values: `C128`, `C64`, `F32`, `F64`, `S16`, `S32`, `S8`, `U1`, `U16`, `U2`, `U32`, `U4`, `U8`, `UNKNOWN`.
`renderingRule` | `Object` |   | A JSON representation of a [raster function](https://developers.arcgis.com/documentation/common-data-types/raster-function-objects.htm)
`mosaicRule` | `Object` |  | A JSON representation of a [mosaic rule](https://developers.arcgis.com/documentation/common-data-types/mosaic-rules.htm)
`token` | `String` |   | If you pass a token in your options it will be included in all requests to the service.
`proxy` | `String` | `false` | URL of an [ArcGIS API for JavaScript proxies](https://developers.arcgis.com/javascript/jshelp/ags_proxy.html) or [ArcGIS Resource Proxies](https://github.com/Esri/resource-proxy) to use for proxying POST requests.
`useCors` | `Boolean` | `true` | If this service should use CORS when making GET requests.
`to` | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) |  | Used to filter what is drawn from the service based on a time range.
`from` | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) |  | Used to filter what is drawn from the service based on a time range.

### Methods

            Method
            Returns
            Description

            bringToBack()
            this
            Redraws this layer below all other overlay layers.

            bringToFront()
            this
            Redraws this layer above all other overlay layers.

            bindPopup({{{param 'Function' 'fn'}}}, {{{param 'PopupOptions' 'popupOptions' 'https://leafletjs.com/reference.html#popup-options'}}})
            this

                Uses the provided function to create a popup that will identify pixel value(s) whenever the map is clicked. Your function will be passed an object with a `pixel` property that is a GeoJSON Point with the pixel value(s) at the clicked location and should return the appropriate HTML. If you do not want to open the popup when there are no results, return false.

imageMapLayer.bindPopup(
  function(err, identifyResults, response){
    var value = results.pixel.properties.value;
    return (value) ? 'Pixel value: ' + value : false;
  });

                NOTE: by default, if the layer has a mosaic rule applied, then the same rule will be applied to the identify request. Conversely, if the layer has a rendering rule applied, that rule is **NOT** applied to the layer so that that the raw pixel value can be returned. If you need specific control over how these rules (and/or other identify parameters) are passed to the identify service, use L.esri.IdentifyImage.

            unbindPopup()
            this
            Removes a popup previously bound with bindPopup.

            getOpacity()
            Float
            Returns the current opacity of the layer.

            setOpacity({{{param 'Float' 'opacity'}}})
            this
            Sets the opacity of the layer.

            getTimeRange()
            Array
            Returns the current time range being used for rendering.

            setTimeRange({{{param 'Date' 'from'}}}, {{{param 'Date' 'to'}}})
            this
            Redraws the layer with the passed time range.

            getBandIds()
            String
            Returns the current band value(s).

            setBandIds({{{param 'Array' 'bandIds'}}} or {{{param 'String' 'bandIds'}}})
            this
            Specify a single band to export, or you can change the band combination (red, green, blue) by specifying the band number.

            getNoData()
            String
            Returns the current no data value.

            setNoData({{{param 'Array' 'noData'}}} or {{{param 'Number' 'noData'}}}, {{{param 'String' 'noDataInterpretation'}}})
            this
            Specify a single value, or an array of values to treat as no data. No data will values will be rendered transparent.
The optional `noDataInterpretation` can be either `esriNoDataMatchAny` | `esriNoDataMatchAll`. The default is `esriNoDataMatchAny` when `noData` is a number, and `esriNoDataMatchAll` when noData is an array. See Image Service Export Image documentation for more details

            getNoDataInterpretation()
            String
            Returns the current no data interpretation value.

            getPixelType()
            String
            Returns the current pixel type.

            setPixelType({{{param 'String' 'pixelType'}}})
            this
            The pixel type, also known as data type, pertains to the type of values stored in the raster, such as signed integer, unsigned integer, or floating point. Possible values: `C128`, `C64`, `F32`, `F64`, `S16`, `S32`, `S8`, `U1`, `U16`, `U2`, `U32`, `U4`, `U8`, `UNKNOWN`.

            authenticate({{{param 'String' 'token'}}})
            this
            Authenticates this service with a new token and runs any pending requests that required a token.

            metadata({{{param 'Function' 'callback'}}}, {{{param 'Object' 'context'}}})
            this

                Requests metadata about this Feature Layer. Callback will be called with `error` and `metadata`.

featureLayer.metadata(function(error, metadata){
  console.log(metadata);
});

            query()
            this

                Returns a new L.esri.Query object that can be used to query this service.

imageService.query()
  .within(latlngbounds)
  .run(function(error, featureCollection, response){
    console.log(featureCollection);
});

            getRenderingRule()
            Object
            Returns the current rendering rule of the layer.

            setRenderingRule({{{param 'Object' 'renderingRule'}}})
            this
            Redraws the layer with the passed rendering rule.

            getMosaicRule()
            Object
            Returns the current mosaic rule of the layer.

            setMosaicRule({{{param 'Object' 'mosaicRule'}}})
            this
            Redraws the layer with the passed mosaic rule.

            redraw()

            Used to make a fresh request to the service and draw the response.

### Events

| Event | Data | Description |
| --- | --- | --- |
| `loading` | [<`LoadingEvent`>]({{assets}}api-reference/events.html#loading-event) | Fires when new features start loading. |
| `load` | [<`LoadEvent`>]({{assets}}api-reference/events.html#load-event) | Fires when all features in the current bounds of the map have loaded. |

`L.esri.ImageMapLayer` also fires all  [`L.esri.ImageService`]({{assets}}api-reference/services/image-service.html) events.

### Example

#### Simple Image Layer

```js
var map = L.map('map').setView([38.83, -98.5], 7);

L.esri.basemapLayer('Gray').addTo(map);

var url = 'https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/World/MODIS/ImageServer';

L.esri.imageMapLayer({
  url: url,
  opacity: 0.25,
  // only necessary for old versions of ArcGIS Server
  useCors: false
}).addTo(map);
```

#### Infrared image layer using bandIds property

```js
var map = L.map('map').setView([43.50, -120.23], 7);

L.esri.basemapLayer('Imagery').addTo(map);

L.esri.imageMapLayer({
  url: 'https://ihttmagery.oregonexplorer.info/arcgis/rest/services/NAIP_2011/NAIP_2011_Dynamic/ImageServer'
})
  .setBandIds('3,0,1')
  .addTo(map);
```


text:
TEST(MisspellingTest, SerializeTest) {
  Misspelling misspelling;
  misspelling.context = ASCIIToUTF16("How doe sit know");
  misspelling.location = 4;
  misspelling.length = 7;
  misspelling.timestamp = base::Time::FromJsTime(42);
  misspelling.hash = 9001;
  misspelling.suggestions.push_back(ASCIIToUTF16("does it"));

  scoped_ptr<base::Value> expected(base::JSONReader::Read(
      "{\"originalText\": \"How doe sit know\","
      "\"misspelledStart\": 4,"
      "\"misspelledLength\": 7,"
      "\"timestamp\": \"42\","
      "\"suggestionId\":\"9001\","
      "\"suggestions\": [\"does it\"],"
      "\"userActions\": [{\"actionType\": \"PENDING\"}]}"));

  scoped_ptr<base::DictionaryValue> serialized(misspelling.Serialize());
  EXPECT_TRUE(serialized->Equals(expected.get()));
}


text:
package com.wut.provider.row;

import com.wut.datasources.TableRowSource;
import com.wut.model.list.ListData;
import com.wut.model.map.MappedData;
import com.wut.model.scalar.BooleanData;
import com.wut.model.scalar.IdData;

public class DefaultTableRowProvider implements TableRowProvider {
	private TableRowSource source;

	public DefaultTableRowProvider(TableRowSource source) {
		this.source = source;
	}

	@Override
	public ListData get(IdData customer, IdData application, IdData tableId) {
		return ListData.convert(source.get(customer.toRawString(), application.toRawString(), tableId.toRawString()));
	}

	@Override
	public ListData filter(IdData customer, IdData application, IdData tableId, MappedData filter) {
		return ListData.convert(source.filter(customer.toRawString(), application.toRawString(), tableId.toRawString(), filter.getMapAsPojo()));
	}

	@Override
	public MappedData get(IdData customer, IdData application, IdData tableId, IdData rowId) {
		return MappedData.convert(source.get(customer.toRawString(), application.toRawString(),tableId.toRawString(), rowId.toRawString()));
	}

	@Override
	public BooleanData delete(IdData customer, IdData application, IdData tableId, IdData rowId) {
		return BooleanData.create(source.remove(customer.toRawString(), application.toRawString(),tableId.toRawString(), rowId.toRawString()));
	}

	@Override
	public BooleanData update(IdData customer, IdData application, IdData tableId, IdData rowId, MappedData data) {
		return BooleanData.create(source.update(customer.toRawString(), application.toRawString(), tableId.toRawString(), rowId.toRawString(), data.getMapAsPojo()));
	}

	@Override
	public BooleanData crupdate(IdData customer, IdData application, IdData tableId, IdData rowId, MappedData data) {
		return BooleanData.create(source.crupdate(customer.toRawString(), application.toRawString(), tableId.toRawString(), rowId.toRawString(), data.getMapAsPojo()));
	}

	@Override
	public IdData insert(IdData customer, IdData application, IdData tableId, MappedData data) {
		return IdData.create(source.insert(customer.toRawString(), application.toRawString(), tableId.toRawString(), data.getMapAsPojo()));
	}

}